What is the output of the following snippet?
def fun(x): if x % 2 == 0: return 1 else: return print(fun(fun(2)) + 1)
- 2
- the code will cause a runtime error
- None
- 1
Explanation: Let’s analyze the code:
- the inner parentheses in the print function are executed first,
- the fun function is invoked with the integer 2 as an argument,
- the if conditional 2 % 2 == 0 returns True, so the fun function returns 1,
- the fun function is invoked with the integer 1 as its argument,
- the if conditional 1 % 2 == 0 returns False, so the fun function returns None,
- The arithmetic operation None + 1 is attempted,
- A runtime error is generated: TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’.
More Questions: Python Essentials 1 – Module 4 Test
Please login or Register to submit your answer