This question will help you test your ability to understand recursive functions in Python.
Contents
Question: Recursive Function Output
What is the output of the following code?
def add(num):
if num == 1:
return 1
return num + add(num - 1)
print(add(4))Answer: C
Explanation:
The add function is initially called with the value 4.
- First, it returns
4 + add(3). - Next, it returns
3 + add(2). - Then, it returns
2 + add(1). At this point,add(1)returns 1.
So, the calculation proceeds as follows:
2 + 1 = 3, which returns to the calladd(2).3 + 3 = 6, which returns to the calladd(3).4 + 6 = 10, which returns to the initial calladd(4).
Thus, the final result is 10.