Stephen
Stephen

Reputation: 7

Recursion used in if else statement

I am new to programming, so I am a little confused about this code, I thought this was supposed to print out:

x is 2 - Going deeper

x is 1 - Going deeper

x is 0 - Turning around

And that was it, since it got to dive(0) and got to the else statement

How come it printed out:

x is 2 - Going deeper

x is 1 - Going deeper

x is 0 - Turning around

x was 1 - Coming back up

x was 2 - Coming back up

The code is:

def dive(x):
    if x > 0:
        print(f'x is {x} - Going deeper')
        dive(x - 1)  
        print(f'x was {x} - Coming back up')
    else:
        print(f'x is {x} - Turning around')  

dive(2)

Upvotes: 0

Views: 282

Answers (1)

litpumpk1n
litpumpk1n

Reputation: 96

Recursion takes place on something called a call stack. So when you first make the recursive call, it is placed on the call stack. Similarly for the subsequent calls you make. Once you reach 0, each function call on the stack is "popped", which is indicated in your code by the "Coming back up" line, since it comes after the recursive call line. In essence, even after you hit the else case the program still has to make its way through the previous recursive calls you made, and won't just exit the program when the else is encountered.

I've attached a screenshot from the python tutor page. Feel free to use it yourself to see how that works step by step! Keep an eye on the output, and the Frames column which represents the recursive call stack. Python Tutor

enter image description here

enter image description here

enter image description here

Upvotes: 2

Related Questions