PCEP-30-02 · Question #223
What is the expected output of the following code? ``python def func(x): if x == 0: return 0 return x + func(x - 1) print(func(3)) ``
The correct answer is A. 6. Option A (6) is correct because func(3) triggers a chain of recursive calls that sum every integer from 3 down to 0: 3 + func(2) → 3 + 2 + func(1) → 3 + 2 + 1 + func(0) → 3 + 2 + 1 + 0 = 6. B (0) is wrong because 0 is only the base-case return value - it gets added back up…
Question
def func(x):
if x == 0:
return 0
return x + func(x - 1)
print(func(3))
Options
- A6
- B0
- C3
- DThe code is erroneous.
How the community answered
(27 responses)- A74% (20)
- B15% (4)
- C7% (2)
- D4% (1)
Explanation
Option A (6) is correct because func(3) triggers a chain of recursive calls that sum every integer from 3 down to 0: 3 + func(2) → 3 + 2 + func(1) → 3 + 2 + 1 + func(0) → 3 + 2 + 1 + 0 = 6.
B (0) is wrong because 0 is only the base-case return value - it gets added back up through the call stack, not returned directly to the caller of func(3). C (3) confuses the input with the output; 3 is just the starting argument, not what the function computes. D is wrong because the code is syntactically and logically valid Python - it terminates correctly at x == 0.
Memory tip: This pattern computes the triangular number formula n(n+1)/2. When you see a recursive function doing x + func(x-1) with a base case of 0, mentally substitute: for func(3), that's 3 × 4 / 2 = 6. This lets you verify the answer instantly without tracing every call.
Community Discussion
No community discussion yet for this question.