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)A. error, there is more than one return statement in a single try-finally block
B. 3
C. 2
D. 1
Answer: Option C
Solution (By Examveda Team)
In the given code, the functionfoo() 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.
Related Questions on Introduction to Python
What is Python primarily used for?
A. Web browsing
B. Data analysis
C. Video editing
D. Game development
Who developed Python Programming Language?
A. Wick van Rossum
B. Rasmus Lerdorf
C. Guido van Rossum
D. Niene Stom
Which of the following is an advantage of Python?
A. It compiles to machine code
B. It enforces strict typing
C. It has a large standard library
D. It requires extensive memory management
What is the role of the Python interpreter?
A. To convert Python code to assembly language
B. To manage memory allocation
C. To execute Python code line by line
D. To compile Python code into bytecode

Join The Discussion