?
What will be the output of the following Python code?
What will be the output of the following Python code?
def foo():
try:
return 1
finally:
return 2
k = foo()
print(k)
def foo():
try:
return 1
finally:
return 2
k = foo()
print(k)
Answer & Solution
Correct Answer:
Option
C
In the given code, the function
Inside the function, there is a
In the
However, before returning, the
As per the behavior of
Therefore, the
When
Hence, the output will be 2.
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.
Join the Discussion
Login to post a comment or share your explanation.
Login