Question 21: Understanding Recursive Function Output in Python

This question will help you test your ability to understand recursive functions in Python.

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:

  1. 2 + 1 = 3, which returns to the call add(2).
  2. 3 + 3 = 6, which returns to the call add(3).
  3. 4 + 6 = 10, which returns to the initial call add(4).

Thus, the final result is 10.

Leave a Reply