Repaso
EspaƱol
PythonAdvancedPY-27

What does this print?

def f():
    try:
        return 1
    finally:
        return 2

print(f())

Options

  1. 1
  2. 2 (Correct option)
  3. 1 then 2
  4. SyntaxError

Answer

2

Why

finally always runs, even after a return in try.

If finally also contains a return, that second return replaces the first one, so f() returns 2. It can even hide exceptions.

That is why a return inside finally is considered a bug; recent Python versions warn about it.

Remember

Never return inside finally.

Key terms

Practice this question in Repaso