Sub topic 2
The Base Case: Knowing When to Stop
This chapter assumes you can write and call Python functions, use if statements, and read short code samples. It covers the part of a recursive function that ends the recursion.
What a base case is
A base case is an input for which the function returns an answer directly, without calling itself. Every chain of recursive calls has to end at a base case. Without one, the calls never stop.
Look at factorial again:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120The line if n == 0: return 1 is the base case. You know the answer for 0 without any further work, so the function returns it right away. Every other input depends on reaching this line eventually.
How to choose a base case
Pick the smallest input that still has a meaningful answer. For numbers this is usually 0 or 1. For a list it is the empty list, and for a string it is the empty string. Then check the base case before any recursive call, so the function stops as soon as it can.
Some functions need more than one base case. Fibonacci uses both 0 and 1, because each step looks two values back:
def fib(n):
if n < 2: # covers n == 0 and n == 1
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55Common errors
| Error | What happens | Fix |
|---|---|---|
| No base case | Calls continue until Python raises `RecursionError` | Add a direct return for the smallest input |
| Base case never reached | Same as above, for some inputs | Make the check cover every input that can arrive |
| Base case after the recursive call | The function recurses before it ever checks | Put the check first |
| Wrong return value | Every result built on it is wrong | Test the base case on its own |
The second error is easy to miss. factorial(-1) steps to -2, then -3, and never equals 0. You can fix this by rejecting the input explicitly:
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(4)) # 24The wrong-value error spreads in the same way. If factorial's base case returned 0, every result would be 0, because each result is a product that includes the base case value.
Exercise
This function should add up the integers from 1 to n. Find the base case problem and fix it. def sumto(n): return n + sumto(n - 1)
Show answer
The function has no base case, so it recurses until RecursionError. Add one before the recursive call: def sumto(n): if n == 0: return 0 return n + sumto(n - 1) sum_to(3) returns 6. For negative n, raise ValueError, because n - 1 moves away from 0.
Exercise
What is a good base case for a recursive function that counts the characters in a string, and what should it return?
Show answer
The empty string, which should return 0. It is the smallest possible input, and its length is known without further work.