Debugging Recursive Functions
You'll learn how to trace and visualize recursive function calls to understand what's going wrong.
Recursive functions can feel like magic—until they don't work. Because they call themselves multiple times and build up a stack of pending operations, bugs can be hard to spot. The secret to debugging recursion is making the invisible visible.
Core Debugging Techniques
Trace Printing
The simplest approach: add print statements that show what's happening at each recursive call. Print the function parameters when entering and the return value when exiting:
def factorial(n):
print(f"→ Entering factorial({n})")
if n <= 1:
print(f"← Base case! Returning 1")
return 1
result = n * factorial(n - 1)
print(f"← Returning {result} from factorial({n})")
return result
factorial(4)
This produces a trace showing the descent into base case and the climb back up with results.
Visualization: Drawing the Call Tree
Sketch out the recursive calls as a tree on paper or mentally. Each node represents one function call, with its parameters. Draw arrows showing which calls spawn which others. This helps you see:
- Whether you're hitting the base case correctly
- If parameters are changing as expected
- Where infinite recursion might occur
Check Common Issues
- Base case missing or wrong? Trace shows calls never stopping.
- Wrong recursive case? Follow the math/logic step-by-step.
- Stack overflow? Count how deep the recursion goes—maybe it's too deep for the input.
Key Takeaway: Debugging recursion means making the call sequence visible through trace printing or drawing call trees—once you see the pattern of calls and returns, logic errors become obvious.