What is the output of the following snippet?
def fun(x): if x % 2 == 0: return 1 else: return 2 print(fun(fun(2)))
- 2
- the code will cause a runtime error
- 1
- 2None
Explanation: The print() function in line 8 takes the fun() function as its argument, which takes another fun() function as its argument, which in turn takes the value 2 as its argument.
Let’s analyze the function calls, starting with the right-most ones:
- the fun(2) call – x is assigned the value of 2, so x % 2 = 0, so the comparison 0 == 0 evaluates to True, and the function returns 1, which is passed to the “left” fun() function as its argument,
- the fun(1) call – x is assigned the value of 1, so x % 2 = 1, so the comparison 1 == 0 evaluates to False, which means the function returns 2, which is passed to the print() function as its argument. Therefore, 2 is printed to the screen.
More Questions: Python Essentials 1 (PE1) Course Final Test
Please login or Register to submit your answer