Learn Python · lesson 51 of 60 · about 8 minutes
Tracing and Fixing Recursion
Follow recursive calls step by step, and fix the classic mistake that makes them go on forever.
What you'll learn
- Trace the calls a recursive function makes
- Recognise a RecursionError
- Make sure each call gets closer to the base case
The 3n + 1 game
The assistant gets a number game for a break. Sam picks a number: if it's even, halve it; if it's odd, times it by 3 and add 1; keep going until it reaches 1. 6 goes 3, 10, 5, 16, 8, 4, 2, 1, so the assistant says 6 reaches 1 in 8 steps, going as high as 16. steps_to_one and highest both work their answers out on the way back up the calls. But some numbers never get to 1: 0 halves to 0 for ever, so the assistant checks with isdigit() that it's a whole number from 1 up before the game starts.
The call stack
When a function calls itself, the first call waits while the new one runs. Python keeps the waiting calls on a pile called the call stack.
Code before the recursive call runs on the way down; code after it runs on the way back up, in reverse order.
Down, then back up
def show(n):
if n == 0:
return
print("down", n)
show(n - 1)
print("up", n)
show(2)Output
down 2
down 1
up 1
up 2When it never stops
If a call never reaches the base case, the stack keeps growing until Python stops it with a RecursionError (maximum recursion depth exceeded). Usually the recursive call isn't making the problem smaller, or the base case can be skipped over.
Catching a runaway
def forever(n):
return forever(n + 1)
try:
forever(0)
except RecursionError:
print("Too deep!")Output
Too deep!Check before you start
Sometimes the base case is right, but some inputs can never reach it. Halving 64 again and again gets to 1; halving 0 never does. When the number comes from someone typing, check it first, so the recursion only ever starts on numbers that will finish. isdigit() is True only for text made of digits, so it says no to -3, 2.5 and words.
Only start on numbers that finish
def halvings(n):
if n == 1:
return 0
return 1 + halvings(n // 2)
for text in ["64", "0", "-8"]:
if text.isdigit() and int(text) >= 1:
print(text, "halves to 1 in", halvings(int(text)), "steps")
else:
print(text, "would never reach 1")Output
64 halves to 1 in 6 steps
0 would never reach 1
-8 would never reach 1Tip
Add a print at the start of a recursive function to see each call's arguments. You'll spot straight away if they aren't heading towards the base case.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.