Why don't this return 1? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Why don't this return 1?

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

15th Apr 2019, 7:44 AM
Thimira Rathnayake
Thimira Rathnayake - avatar
6 Answers
+ 8
If a function returns something, it means that the return value is saved somewhere and the control flow jumps back to the piece of code where the function was called from. However, here the return statement is embedded in a try block and the function can't just jump back, but the finally block has to be evaluated first. Within the finally block, there is a different return value so this is what will be returned.
15th Apr 2019, 9:21 AM
Anna
Anna - avatar
+ 7
When an exception handling `try` block has a `finally` block, the `finally` block is executed despite there was any or no exception captured. Hth, cmiiw
15th Apr 2019, 8:12 AM
Ipang
+ 2
Because the 'finally' block returns 2. And it overrides the 1 that returned within the 'try' block.
16th Apr 2019, 5:28 AM
Kosala Gangabadage
Kosala Gangabadage - avatar
+ 2
Thanks! Anna
16th Apr 2019, 5:40 AM
Thimira Rathnayake
Thimira Rathnayake - avatar
+ 2
Thanks! Kosala
16th Apr 2019, 5:41 AM
Thimira Rathnayake
Thimira Rathnayake - avatar
+ 1
Thanks! Ipang
16th Apr 2019, 5:41 AM
Thimira Rathnayake
Thimira Rathnayake - avatar