ExamVeda
Login
Home
Introduction to Python
?

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

Answer & Solution
Correct Answer: Option C
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.
Examveda
Question posted by Examveda
Community

Join the Discussion

No comments yet Be the first to discuss this question.