Sub topic 5
Tracing a Recursive Function Step by Step
This chapter assumes you can read basic Python, know what a base case and a recursive case are, and have seen how each call gets its own stack frame on the call stack. Here you turn that model into a practical skill. You will learn to follow a recursive function by hand, print a trace from running code, and spot the mistakes people usually make when they reason about recursive calls.
Tracing means recording, call by call, which arguments each frame receives, what work it leaves pending, and what value it returns. Do it carefully a few times. After that you can switch to the faster reasoning style covered in the next chapter.
The Two Phases of Every Trace
Every recursive execution has two phases, and most tracing errors come from mixing them up.
- The descent (winding) phase. Calls are made one after another, each with a smaller input. Each frame stops at its recursive call and waits. Any code before the recursive call runs during this phase.
- The ascent (unwinding) phase. The base case returns, and the waiting frames resume one by one, newest first. Any code after the recursive call runs during this phase.
The countdown function makes the two phases visible:
def countdown(n):
if n < 0:
return
print("enter", n)
countdown(n - 1)
print("exit", n)
countdown(2)
# enter 2
# enter 1
# enter 0
# exit 0
# exit 1
# exit 2The enter lines appear in call order because they print during the descent. The exit lines appear in reverse order because each one prints only after every deeper call has finished. The call countdown(-1) hits the base case and prints nothing, so it can be easy to miss. It is still a real frame.
Method 1: The Substitution Model
For functions that return a value, the quickest hand trace is to substitute each call with its definition until you reach the base case, then simplify. Here is factorial:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(3)) # 6Expanding factorial(3):
factorial(3)
= 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0)))
= 3 * (2 * (1 * 1))
= 3 * (2 * 1)
= 3 * 2
= 6The expression grows during the descent and shrinks during the ascent. The parentheses stand for pending work. Each n * that has not yet been applied belongs to a frame that is still on the stack. The widest line shows the deepest stack, which here is four frames.
The substitution model works well for pure functions that compute a value without printing or changing shared state. It breaks down once a function has side effects, because the order of those effects matters and an expression does not show it.
Method 2: The Trace Table
A trace table gives each frame one row. It lists the arguments, the pending work, and the return value. Fill the "returns" column from the bottom up.
| Frame | n | Pending work | Returns |
|---|---|---|---|
| factorial(3) | 3 | 3 * (result of factorial(2)) | 6 |
| factorial(2) | 2 | 2 * (result of factorial(1)) | 2 |
| factorial(1) | 1 | 1 * (result of factorial(0)) | 1 |
| factorial(0) | 0 | none (base case) | 1 |
Each row has its own n. When factorial(1) runs, the n in the factorial(3) frame is still 3. Local variables are never shared between frames, even though they have the same name.
The same calls and returns can be drawn as a sequence of messages:
Method 3: Let the Program Trace Itself
Hand traces are good for learning. For real debugging you want the program to print its own trace. You can pass a depth parameter and indent output by it:
def factorial(n, depth=0):
indent = " " * depth
print(f"{indent}factorial({n}) called")
if n == 0:
print(f"{indent}base case -> 1")
return 1
result = n * factorial(n - 1, depth + 1)
print(f"{indent}factorial({n}) returns {result}")
return result
factorial(3)
# factorial(3) called
# factorial(2) called
# factorial(1) called
# factorial(0) called
# base case -> 1
# factorial(1) returns 1
# factorial(2) returns 2
# factorial(3) returns 6The indentation level equals the number of frames above the current one, so the output draws the stack. Notice that the result is stored in a variable before it is printed. Without that variable, you could not log the return value.
Adding a depth parameter changes the function's signature. A decorator avoids that by wrapping any recursive function without editing it:
import functools
def trace(func):
depth = 0
@functools.wraps(func)
def wrapper(*args):
nonlocal depth
indent = "| " * depth
arg_text = ", ".join(repr(a) for a in args)
print(f"{indent}{func.__name__}({arg_text})")
depth += 1
try:
result = func(*args)
finally:
depth -= 1
print(f"{indent}-> {result!r}")
return result
return wrapper
@trace
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
factorial(3)
# factorial(3)
# | factorial(2)
# | | factorial(1)
# | | | factorial(0)
# | | | -> 1
# | | -> 1
# | -> 2
# -> 6The decorator works because the name factorial inside the function body refers to the wrapped version, so every recursive call also goes through wrapper. The try/finally keeps depth correct even if a call raises an exception.
Common Tracing Mistakes
These are the errors that show up most often when people trace recursion by hand:
- Stopping at the base case. The base case's return value is usually not the final answer. Every waiting frame still has to finish its pending work.
- Assuming returns happen in call order. Returns happen in reverse call order. The first call made is the last to return.
- Merging frames' variables. Each frame has its own copy of its parameters and locals. If you write a single
nin the margin and keep overwriting it, the trace will be wrong. - Forgetting the silent base-case frame. In
countdown, the call withn = -1prints nothing, but it still counts toward stack depth. - Tracing with inputs that are too big. Use the smallest input that reaches the recursive case once or twice, usually 2 or 3. Bigger inputs only repeat the same pattern.
- Ignoring where side effects sit. Moving one
printfrom before the recursive call to after it reverses the output order. The next example shows this.
Before or After: One Line Changes the Order
Both functions below print the decimal digits of a non-negative integer. The only difference is where the print sits relative to the recursive call.
def digits_forward(n):
if n < 10:
print(n)
return
digits_forward(n // 10)
print(n % 10)
def digits_backward(n):
if n < 10:
print(n)
return
print(n % 10)
digits_backward(n // 10)
digits_forward(123) # prints 1, 2, 3 on separate lines
digits_backward(123) # prints 3, 2, 1 on separate linesIn digits_forward, each frame prints its last digit during the ascent, after the deeper frames have printed the leading digits. In digits_backward, each frame prints its last digit during the descent, so the lowest digit comes out first.
Exercise
Trace mystery(5) and give its return value. Then say how many frames are created in total.
def mystery(n):
if n <= 0:
return 0
return n + mystery(n - 2)
Show answer
mystery(5) = 5 + mystery(3) = 5 + (3 + mystery(1)) = 5 + (3 + (1 + mystery(-1))) = 5 + (3 + (1 + 0)) = 9. Four frames are created: mystery(5), mystery(3), mystery(1), and mystery(-1). The last one hits the base case because -1 <= 0. The input skips over 0 here, and the function still stops only because the base case uses <= instead of ==.
Exercise
For countdown(3) from the start of this chapter, how many lines are printed, and what is the fifth line? How many frames are on the stack at the deepest point, counting only countdown frames?
Show answer
Eight lines are printed: enter 3, enter 2, enter 1, enter 0, exit 0, exit 1, exit 2, exit 3. The fifth line is "exit 0". The deepest point has five countdown frames, for n = 3, 2, 1, 0, and -1, where the n = -1 frame returns without printing.
Exercise
Apply the @trace decorator to digits_forward and call digits_forward(42). Write the complete output, including the lines printed by the function itself.
Show answer
The output is: digitsforward(42) | digitsforward(4) 4 | -> None 2 -> None The inner call prints the trace line, then the base case prints 4, then the wrapper logs its return of None. Back in the outer frame, print(42 % 10) prints 2, and the wrapper logs the outer return of None. The digit lines are not indented because the function's own print knows nothing about depth.