PCEP-30-02 · Question #188
What is the expected output of the following code? def func(x): if x % 2 == 0: return 1 else: return print(func(func(2)) + 1)
The correct answer is D. The code is erroneous. Option D is correct because the code raises a TypeError at runtime: func(2) returns 1 (since 2 is even), then func(1) hits the else branch and returns None (a bare return in Python always returns None), and finally None + 1 causes a crash since you cannot add NoneType and int…
Question
Options
- ANone
- B1
- C2
- DThe code is erroneous.
How the community answered
(47 responses)- A13% (6)
- B4% (2)
- C2% (1)
- D81% (38)
Explanation
Option D is correct because the code raises a TypeError at runtime: func(2) returns 1 (since 2 is even), then func(1) hits the else branch and returns None (a bare return in Python always returns None), and finally None + 1 causes a crash since you cannot add NoneType and int.
- A (None) is wrong because the code never silently produces
Noneas output - the+ 1operation onNonecrashes before anything can be printed. - B (1) and C (2) are wrong for the same reason: the
TypeErrorprevents theprintfrom ever executing, so no numeric result is produced.
Memory tip: Whenever you see a bare return (no value) in Python, mentally substitute return None - then ask yourself what happens when that None is used in an arithmetic expression. If it's added, subtracted, or multiplied with a number, it's always a TypeError.
Community Discussion
No community discussion yet for this question.