Lesson · Functions
Recursion
60 min readRecursion
Recursion solves a problem by reducing it to smaller instances of the same problem. Python supports recursion but does not optimize tail calls, so depth and stack usage are practical constraints.
Learning goals
- Trace
factorial(5)frame by frame and explain what each waiting frame is holding. - Identify the base case and say what a missing or unreachable one causes.
- Prove that a recursive step makes progress by pointing to the shrinking argument.
- Explain why negative input raises
ValueErrorhere while deep input raisesRecursionErrorinstead. - Decide when the iterative version is the safer choice in Python.
Mental model
Recursion has three moving parts: a base case that returns without calling again, a recursive step that must move toward it, and the call stack that holds every frame still waiting for its result. The fence shows both halves of the journey, the descending calls on the way down and the multiplications on the way back up, and the depth is simply how many frames are alive at the deepest point.
Down the calls, then back up the products
the base case is what stops the descent
Mental model
the same mechanism as a compact list
factorial(5) ↓ calls factorial(4) and waits 5 frames active at the deepest point factorial(4) → factorial(3) → factorial(2) → factorial(1) ↓ the base case returns 1 without calling again factorial(2) = 2 * 1 = 2 factorial(3) = 3 * 2 = 6 ↑ the stack unwinds in reverse order factorial(5) = 5 * 24 = 120
Core idea
Recursion works like a proof: the base case supplies the starting truth, and the recursive step shows that a smaller instance explains the current one, so a step that genuinely shrinks the problem must terminate at the base. Python keeps the chain of unfinished calls on the call stack, one frame per level, which is why depth is a real cost and why a too-deep or non-progressing recursion ends in RecursionError.
Base case
The base case stops recursive decomposition and returns a direct result. Without a reachable base case, recursion continues until an error such as RecursionError occurs.
Recursive step
The recursive step must move the problem toward the base case. Prove that the input measure decreases or otherwise progresses on every recursive path.
Call stack
Each active function call has execution state on the call stack. Recursive algorithms therefore consume stack depth proportional to the longest active recursion path.
Recursive depth
Each recursive call adds another active frame. Depth therefore consumes memory and eventually reaches an interpreter recursion limit if the base case is too far away.
Recursion limits
Python protects the interpreter with a recursion-depth limit. Raising the limit is not a substitute for converting naturally deep linear recursion to iteration.
Recursive vs iterative solutions
This comparison separates Recursive from iterative solutions in the context of Recursion. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
Tail recursion and Python
CPython does not perform tail-call elimination. A tail-recursive function still consumes one Python frame per call, so iteration is often safer for long linear recursions.
Walkthrough
factorial(n)first rejects negative inputs withValueError, then checks the base casen <= 1, which returns1without calling anything else.return n * factorial(n - 1)is the recursive step: the argument drops by one on every call, sofactorial(5)reaches the base case after four further calls.- The multiplication is deferred:
factorial(5)cannot return untilfactorial(4)returns, and so on down the chain, so five frames are active at the deepest point and the products build back up to120. - Predict before running: the value of
factorial(5), the value offactorial(1), and what happens if then <= 1check is deleted.
Experiments to try
- Call
factorial(1)andfactorial(0); both return1, which shows the base case covering two boundary values, then callfactorial(-1)and read theValueError. - Add
print(n)as the first statement offactorialand runfactorial(4); the printed sequence descends from 4 to 1 and stops, because the prints happen on the way down, not on the way up. - Delete the
n <= 1check, runfactorial(5), and read theRecursionError; then restore the check. - Write the iterative version with a
forloop and run both versions onfactorial(0)throughfactorial(10); then tryfactorial(1000)on the recursive version and explain the failure against the loop's success.
Playable lesson
Lab: Recursion stack
Render one stack frame per recursive call, with local variables and return values. Step into and out of calls.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Recursion stack
Call stack (newest on top)
- factorial(5)waiting
Depth
1
frames still waiting
Result
not returned yet
Predict first
How many frames are alive at the deepest point of `factorial(5)`?
One call starts. `factorial(5)` checks its guards, then reaches the recursive step, which means it cannot return until another call returns.
Calls descend first; the multiplications only happen on the way back up.
Common mistakes
- Removing or unreachable base case: every call starts another before it can return, so the chain descends until the interpreter hits its recursion limit and raises
RecursionError. - A recursive step that does not shrink the problem, such as calling
factorial(n)instead offactorial(n - 1): the base case exists but nothing ever approaches it, with the sameRecursionErroras the symptom. - Ignoring depth costs: Python keeps one frame per call and does not optimize tail calls, so a correct linear recursion over a huge input raises
RecursionErrorwhere a loop would have finished. - Dropping the operation around the recursive call, returning
factorial(n - 1)without then *: the function still ends, but it returns1for every valid input instead of the product.
Practice: Easy
- Run
print(factorial(5))and write the five multiplications in the order they are performed during unwinding; state which call produced each product. - Call
factorial(0),factorial(1), andfactorial(-1); record the two return values and the exception, and name the guard responsible for each. - Add
print(n)as the first statement offactorialand runfactorial(4); write down the sequence and mark where the returns happen.
Practice: Medium
- Rewrite
factorialwith aforloop, confirm both versions agree onfactorial(0)throughfactorial(10), and state which version fails first as the input grows. - Write
def total(values): return 0 if not values else values[0] + total(values[1:]), run it on a list of five numbers, and explain why the empty list is the base case. - Add a
depth=0parameter tofactorialthat prints on entry, runfactorial(4), and confirm the printed depths match the number of active frames you predicted.
Practice: Hard
- Find the largest
nfor whichfactorial(n)still returns before raisingRecursionError; compute the same values with an iterative loop that has no depth problem, and state what the difference measures. - Break the function in two different ways (delete the base case; recurse on
ninstead ofn - 1), run each, capture theRecursionError, and explain why the same error appears for two different bugs. - Write a recursive
count_items(data)that counts every item in arbitrarily nested lists, with the empty list as the base case; run it on[1, [2, 3], [4, [5]]], then convert the same function to iteration with an explicit stack and compare the two versions.
Lesson checklist
- I can trace
factorial(5)as five descending calls and five returning products. - I can point to the base case in a recursive function and say what happens without it.
- I can explain how the call stack holds waiting frames and why depth costs memory.
- I can convert a simple linear recursion to a loop when depth becomes the problem.
Remember
Recursion reduces a problem to a smaller copy of itself: the base case supplies the stop, the recursive step shrinks the input, and the call stack holds one waiting frame per level until the results unwind. Python does not optimize tail calls, so depth is a genuine constraint, and anything that keeps a recursion from making progress ends the same way, in a `RecursionError`.
Interview angles
What is the main purpose of **Base case**?+
The base case stops recursive decomposition and returns a direct result. Without a reachable base case, recursion continues until an error such as RecursionError occurs.
What should you pay attention to when using **Recursive step**?+
The recursive step must move the problem toward the base case. Prove that the input measure decreases or otherwise progresses on every recursive path.
How does **Call stack** fit into this lesson?+
Each active function call has execution state on the call stack. Recursive algorithms therefore consume stack depth proportional to the longest active recursion path.
Why does removing the base case from `factorial` end in `RecursionError` instead of a wrong number?+
Because each call starts another call before it can return, so the chain never stops descending. Python keeps one frame per active call and raises RecursionError when the depth reaches the interpreter's limit; the error reports a stack-depth failure, not a mistake in the multiplication.