Vidyalelo
Python · Q48

Python Introduction and basic

Programming · Python · question 48

Q48

What will be the output of the following Python code? def foo(): try: return 1 finally: return 2 k = foo() print(k)

A.
error, there is more than one return statement in a single try-finally block
B.
3
C.
2
Answer
D.
1

Answer: Option C

Solution

Answer: Option C
Solution:
In the given code, the function foo() is defined.
Inside the function, there is a try-finally block.
In the try block, return 1 is encountered.
However, before returning, the finally block executes, which contains return 2.
As per the behavior of finally, it always executes, regardless of whether there is an exception or not.
Therefore, the return 2 statement in the finally block is executed, and 2 is returned from the function.
When foo() is called and its return value is assigned to k, k will be 2.
Hence, the output will be 2.