What happens step by step
-
The function f() is called.
-
Python enters the try block.
return 10 is executed — Python prepares to return 10, but does not exit the function yet.
-
Before the function actually returns, Python must execute the finally block.
-
The finally block contains return 20.
-
This new return overrides the previous return 10.
-
So the function returns 20.
print(f()) prints 20.
✅ Final Output
20Key Rule
If a finally block contains a return, it always overrides any return from try or except.
Important takeaway
Using return inside finally is usually discouraged because:
-
It hides exceptions
-
It overrides earlier returns
-
It can make debugging very confusing
100 Python Projects — From Beginner to Expert
In short
| Block | What it does |
|---|---|
| try | Prepares return 10 |
| finally | Executes and overrides with return 20 |
| Result | 20 |


0 Comments:
Post a Comment