Sub topic 5
Tracing a Recursive Function Step by Step
This chapter assumes you can read Python functions and conditionals. It also assumes you know from the previous chapter that each call gets its own stack frame. Tracing means following a recursive function call by call, writing down what each frame knows and what it returns. You do this by hand to check a function or to find a bug before you trust it.
A Repeatable Tracing Method
Use the same steps every time:
- Write the call you start with, such as
factorial(3). - Note the parameter values for this frame.
- If the base case applies, record the return value and stop going down.
- Otherwise, write the pending expression, such as
3 * factorial(2), and trace the inner call one level deeper. - When an inner call returns, put its value into the pending expression of the frame above it.
The calls go down until they reach the base case. The results then come back up.
Tracing Factorial by Hand
Start from this definition:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)A trace table for factorial(3) looks like this:
| Frame | n | Pending work | Returns |
|---|---|---|---|
| factorial(3) | 3 | 3 * factorial(2) | 6 |
| factorial(2) | 2 | 2 * factorial(1) | 2 |
| factorial(1) | 1 | 1 * factorial(0) | 1 |
| factorial(0) | 0 | none (base case) | 1 |
Read the "Pending work" column from top to bottom. Read the "Returns" column from bottom to top.
Letting the Program Trace Itself
A larger trace is easier to follow if the function prints it for you. Add a depth parameter and use it to indent each line:
def factorial(n, depth=0):
indent = " " * depth
print(f"{indent}factorial({n})")
if n == 0:
print(f"{indent}return 1")
return 1
result = n * factorial(n - 1, depth + 1)
print(f"{indent}return {result}")
return result
factorial(3)
# factorial(3)
# factorial(2)
# factorial(1)
# factorial(0)
# return 1
# return 1
# return 2
# return 6Each return line sits at the same indentation as the call it finishes. That makes it easy to match calls with their results.
Common Tracing Errors
- Mixing up frames. Each frame has its own
n. Whenfactorial(1)runs,ninfactorial(3)is still 3. - Forgetting the pending work. The multiplication
n * ...does not happen on the way down. It happens on the way back up, after the inner call returns. - Skipping the base case check. Check the base case condition with the actual argument each time. If no argument ever meets it, the trace never ends, and the real program fails the same way.
Exercise
Trace this function for mystery(3) and give the printed output in order. def mystery(n): if n == 0: return mystery(n - 1) print(n)
Show answer
It prints 1, 2, 3, one per line. The calls go down from 3 to the base case at 0 without printing anything. Each print runs after its inner call returns, so the deepest frame with output, mystery(1), prints first.
Exercise
Using a trace table, what does factorial(4) return, and how many frames are on the stack when the base case runs?
Show answer
It returns 24. Five frames are on the stack at that point: factorial(4), factorial(3), factorial(2), factorial(1), and factorial(0).