If you understand stack very well then you will understand how memory works in program and if you understand how memory works in program you will understand how function store in program and if you understand how function store in program you will understand how recursive function works and if you understand how recursive function works you will understand how compiler works and if you understand how compiler works your mind will works as compiler and you will debug any program very easily
Let me explain how stack works:
First you have to know how function store in stack :
Heap store dynamic memory allocation values.
Stack store automatic allocation and deletion values.
Let's understand with example :
def hello(x):
if x==1:
return "op"
else:
u=1
e=12
s=hello(x-1)
e+=1
print(s)
print(x)
u+=1
return e
hello(4)
Now understand parts of this program :
Now let's see what is stack and what are stack parts:
Allocation of the stack :
Remember one thing if any function get “return” no matter it have loaded all his local varibles or anything it will immediately return from stack will his stack frame. It means when any recursive function get base condition and we put return after base condition so base condition will not wait to load local variables which are situated in “else” part of program it will immediately return current frame from the stack and now if one frame return next frame is in activation record.
See this in practical:
Deallocation of the block:
So now whenever a function found return statement it delete current frame from the stack.
while returning from the stack value will return in reverse order of order in which they allocated in stack.
These are very short description and if you want to know more deep about stack and double recursion read two post of this blog :
More about stack step by step
More about Double recursion step by step with stack