I am quite confused with the code below.
def a(x):
print(x)
if x > 0:
a(x - 1)
print(x) #I am confused with this print statement
a(5)
The above code outputs:
5
4
3
2
1
0
0
1
2
3
4
5
Up till the 0 I understand how it prints, but then why it prints in ascending order.
Variable x is changing so what I thought the output would be is the last assigned value of x that is 0.
My predicted output:
5
4
3
2
1
0
0
0
0
0
0
0
So how does it track the value of x...?
Can someone explain in brief what actually happens in recursive functions and how variables are stored in it.
xis not changing: each function call has its ownx.x - 1does not alter the value ofxin the current scope. You may find pythontutor.com useful.