Interview Q&A / Python

AdvancedQuick answer1 min readUpdated 3 Oct 2026

What does this function return when both try and finally have a return statement?

SHORT ANSWER

It returns the value from the finally block. finally always runs last, and a return inside it overrides the earlier return and even discards a pending exception. This is why returning from finally is considered bad practice.

Explain it simply

You hand a letter to a courier at the door (the return in try). Before he leaves, the security guard (finally) takes it and gives him a different letter. The courier delivers whatever the guard gave him last.

Example

python
def f():
    try:
        return "try"
    finally:
        return "finally"

print(f())      # Output: finally

def g():
    try:
        raise ValueError("boom")
    finally:
        return "swallowed"

print(g())      # Output: swallowed

def h():
    x = 1
    try:
        return x
    finally:
        x = 2

print(h())      # Output: 1

In h, the return value 1 is already fixed when return x runs. Changing x in finally is too late to alter it.

What to say in the interview

"finally always executes before the function really returns. If finally itself contains a return, that value wins and any exception in flight is silently dropped. I never return or break inside finally; I use it only for cleanup."

Common mistakes

  • Assuming a return in try ends the function immediately, skipping finally.

#python#exceptions#output-puzzles

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.