1.2.39 · D3Introduction to Programming (Python)

Worked examples — Recursion depth limit — stack overflow

3,973 words18 min readBack to topic

Look at the picture below: it traces the exact function of Example 1, countdown(3). Read it top-to-bottom: each call lays down one black plate, and the moment the base case countdown(0) fires (the red plate) is the tallest the stack ever gets — four plates high. The dashed line near the top is the ~1000-frame limit; this little example is nowhere near it, but every crash on this page is just this same picture grown past that line.

Figure — Recursion depth limit — stack overflow

We will refer back to this "plate pile" repeatedly — it is the mental model behind every cell of the matrix.


The scenario matrix

Every recursion problem lands in one of these cells. The examples below are labelled with the cell they cover.

Cell Situation What decides the outcome
A Base case present and reached, depth < limit Runs fine, returns a value
B Base case correct but depth > limit RecursionError even though logic is right
C Base case missing (infinite) RecursionError fast, always
D Base case exists but never approached RecursionError — the sneaky bug
E Zero / degenerate input (n = 0, empty list) Hits base immediately, depth = 1
F Negative / wrong-direction input Overshoots the base, runs away
G Branching recursion (calls itself twice) Depth ≠ number of calls — depth is the tallest path
H Limit raised deliberately for deep-but-finite work Runs, but risks a hard segfault
I Real-world word problem Translate story → depth
J Exam twist — count exact frames, off-by-one The 1000 is total frames, not per-function
K Mutual (co-)recursionis_evenis_odd Two functions bounce; depth is the combined chain, still one shared stack

The single idea threaded through all of them. First one symbol to earn:


Cell A + E — base reached, and the degenerate input


Cell C — no base case (pure infinite)

The figure below overlays two runs on the same plate-height axis: the healthy countdown (black, rises to then falls) versus boom (red, climbs forever straight through the dashed limit line). This single picture is the shape of every runaway on this page — Cells C, D and F all trace that red line.

Figure — Recursion depth limit — stack overflow

See Recursion — base case and recursive case — Cell C is exactly "forgot the base case".


Cell D — base exists but is never approached (the sneaky one)


Cell F — wrong-direction / negative input


Cell G — branching recursion (depth ≠ call count)

Figure — Recursion depth limit — stack overflow

Cell B + J — correct logic, depth over the limit, exact-count twist


Cell A (iterative escape) — one frame forever


Cell K — mutual (co-)recursion, one shared stack


Cell H — raising the limit for deep-but-finite work


Cell I — a real-world word problem


Cell A + Exceptions — catch it and recover


The 80/20 of every cell


Connections