The call stack
🌍 In real life. In a canteen, clean plates are stacked: you put a plate on top, and you take a plate from the top. The plate at the bottom went in first and comes out last. Nobody pulls a plate out of the middle.
Python keeps its waiting function calls in exactly that kind of pile, called the call stack.
The idea in one sentence: every call gets its own frame on top of the call stack, waits there while the calls it makes run, and is removed when it returns its answer.
Its words:
- frame: one call's box of parameters and local variables
- call stack: the pile of frames for all the calls still running
- push / pop: a new call is pushed on top; a returning call is popped off
- RecursionError: Python's stop when the stack gets about 1000 frames deep
Step by step, for dive(2):
dive(2)prints "going down 2" and callsdive(1): a new frame goes on top.dive(1)does the same and callsdive(0), which prints "bottom!" and returns.- Back in
dive(1), the line after the call runs: "coming back 1". Thendive(2)prints "coming back 2".
Code written after the recursive call runs on the way back up, once the deeper calls have finished. Watch the order here:
def dive(n):
if n == 0:
print("bottom!")
return
print("going down", n)
dive(n - 1)
print("coming back", n)
dive(3)If the calls never reach a base case, frames pile up forever. Python stops at about 1000 frames with a RecursionError:
def countdown(n):
return countdown(n - 1)
countdown(3)Why the stack has a limit. Every frame uses memory, and a recursion that never stops would use all of it. So Python refuses to go deeper than about 1000 frames and stops with a RecursionError instead of freezing. That also means recursion isn't a good fit for problems that are thousands of steps deep, like counting down from 100,000; a loop has no such limit.
Mistakes and edge cases.
- No base case.
RecursionError: maximum recursion depth exceeded(above). - Expecting lines after the call to run first. They run on the way back up, after every deeper call has finished, so their output comes in reverse order.
- Recursing too deep on purpose. Even a correct recursion fails past about 1000 levels; use a loop for long chains.
- Looking for a stopped call's local variables. Once a frame is popped, its names are gone.
Quiz
What does this print?
def dive(n): if n == 0: return print("down", n) dive(n - 1) print("up", n) dive(2)What happens when a recursive function never reaches its base case?
- Python stops it with a RecursionError
- It runs forever without any error
- It returns None
What does this print?
def show(n): if n == 0: return show(n - 1) print(n) show(3)With
totalfrom the animation, how many frames are on the stack whiletotal(0)runs, if we started withtotal(3)?- 4
- 3
- 1
Which line has a mistake?
def countdown(n): if n == 0: print("Go!") return print(n) countdown(n + 1) countdown(3)
Coding tasks
Write a recursive
digit_sum(n)that returns the sum of the digits of a whole number n ≥ 0. For example,digit_sum(1234)is 10.Write a recursive
count_digits(n)that returns how many digits a whole number n ≥ 0 has.count_digits(0)is 1.