user2673217
user2673217

Reputation: 13

Explain the call stack of this function?

I have the code:

def recursion0(x):
    if x == 1:
        return 1
    else:
        recursion0(x-1)
        print x

I know values 2-x will print, but I cannot figure out how to map the call stack. Below are my thoughts.

Let's set x = 3. 3 goes to 2 in recursion0(3-1), and then 2 goes to 1 in recursion0(2-1). Is 1 then returned to the function that called it, recursion0(2-1), and then 2 is printed because it is the x value? What happens after this so 3 is printed? Another question, why does x print after 1 is returned (and not before)?

Upvotes: 0

Views: 55

Answers (1)

Hyperboreus
Hyperboreus

Reputation: 32429

Your call to recursion0(3) will not return 1, but None, because your else path doesn't return anything.

To fix it, change recursion0(x-1) to return recursion0(x-1).

As your print comes after the recursion, the printing order is the opposite of the calling order.


I want values from 1-x printed, and how does this process work?

def recursion0(x):
    if x == 0: return
    recursion0(x-1)
    print (x)

recursion0(3)

Output is:

>>> 
1
2
3

Upvotes: 3

Related Questions