When recursion doesn't work, add print statements to trace calls:
def factorial(n, depth=0):
indent = " " * depth
print(f"{indent}factorial({n})")
if n == 0:
print(f"{indent}-> returns 1")
return 1
result = n * factorial(n - 1, depth + 1)
print(f"{indent}-> returns {result}")
return result
The depth parameter creates indentation showing the call hierarchy.
Common issues to check:
- Is the base case correct?
- Does each call progress toward the base case?
- Are you returning the recursive result?
Remove debug prints once fixed, or use Python's logging module to toggle them.