Sub topic 2
How the Call Stack Runs Recursive Calls
This chapter assumes you can write and call Python functions, read conditionals, and follow a function's return value back to its caller. It shows what the computer does when a function calls itself, so that you can trace any recursive call and predict its result before you run it.
Each call gets its own frame
When a function is called, Python creates a stack frame. A stack frame is a record holding that call's parameters, its local variables, and the point in the caller where execution should resume. Frames are kept on the call stack, which works last-in, first-out: the newest call sits on top. Only the frame on top is running at any moment.
A recursive call gets no special treatment. When sum_to(3) calls sum_to(2), Python pushes a new frame with its own n. The n = 3 in the older frame is untouched. It waits, paused partway through its expression, until the call above it returns.
The process has two phases:
- Winding: each call pushes a frame and waits on the next call, until a base case is reached.
- Unwinding: the base case returns a value, its frame is popped, and each waiting frame finishes its own work with that value and returns in turn.
Watching the stack grow and shrink
The function below adds up 1 + 2 + ... + n. The depth parameter is only there to indent the output, so each printed line shows how deep the stack is at that moment.
def sum_to(n, depth=0):
indent = " " * depth
print(f"{indent}call sum_to({n})")
if n == 0:
print(f"{indent}return 0")
return 0
result = n + sum_to(n - 1, depth + 1)
print(f"{indent}return {result}")
return result
print(sum_to(3))Output:
call sum_to(3)
call sum_to(2)
call sum_to(1)
call sum_to(0)
return 0
return 1
return 3
return 6
6The indentation moves right while frames are pushed and left while they are popped. The addition n + ... in each frame cannot happen until the inner call returns, so every addition takes place during unwinding.
A stack snapshot table
When you trace by hand, write down the stack at each step. Top of stack is on the left.
| Step | Stack (top first) | Event |
|---|---|---|
| 1 | sum_to(3) | call |
| 2 | sum_to(2), sum_to(3) | call |
| 3 | sum_to(1), sum_to(2), sum_to(3) | call |
| 4 | sum_to(0), sum_to(1), sum_to(2), sum_to(3) | base case returns 0 |
| 5 | sum_to(1), sum_to(2), sum_to(3) | returns 1 |
| 6 | sum_to(2), sum_to(3) | returns 3 |
| 7 | sum_to(3) | returns 6 |
For an input n, the deepest point has n + 1 frames. Stack memory therefore grows linearly with n, which becomes important when the tutorial covers depth limits.
Common tracing errors
- Sharing variables between frames. Every frame has its own
n. Changingnin one call does not affect another. - Assuming code after the recursive call runs right away. Statements after the call run only during unwinding, in reverse order of the calls.
- Missing or unreachable base case. If no call ever reaches the base case, frames keep piling up until Python raises
RecursionError.
Exercise
What does show(3) print, and why? def show(n): if n == 0: return; show(n - 1); print(n)
Show answer
It prints 1, 2, 3 on separate lines. The print comes after the recursive call, so no frame prints until show(0) returns. Frames then unwind from the most recent call, which is n = 1, back to the first call, n = 3.
Exercise
How many sumto frames are on the stack at the deepest point of sumto(4), and what value does the frame for n = 2 return?
Show answer
Five frames, for n = 4, 3, 2, 1, 0. The frame for n = 2 returns 2 + sum_to(1) = 2 + 1 = 3.