The call stack
Not met yet
When a function calls another, it stops on that line and waits, with its variables kept. Python piles the waiting calls up as the call stack: the newest on top, and only the top one running. When the top call returns, it comes off the pile and the one below carries on from where it stopped. So recursive calls finish newest first, and anything after the recursive call runs on the way back out. The pile is only allowed about a thousand calls high; past that, Python stops with a RecursionError.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks the lines after a recursive call never run, as if the call jumped away and left the old call behind.
- Thinks waiting calls finish in the order they started, rather than the newest first.
- Thinks a recursive call runs after the current call finishes, rather than straight away on its own line.
- Thinks a recursion only stops when the computer runs out of memory, rather than at Python's limit of about a thousand waiting calls.