Sub topic 2
The Base Case: Knowing When to Stop
This chapter assumes you can write and call Python functions, use if statements and loops, and work with basic lists. It also assumes you have seen the idea from the previous chapter: a recursive function is one that calls itself. Here we look at the part of a recursive function that does not call itself, and why getting it right decides whether the function works at all.
What a Base Case Is
A base case is an input for which a recursive function returns an answer directly, without making another recursive call. Every chain of recursive calls has to end at a base case. If it never does, the function keeps calling itself until the program runs out of room.
Here is factorial, the standard first example:
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. For n == 0 the function knows the answer immediately. For any other input it hands off part of the work to a smaller call. The base case is where that handing off stops.
A useful way to think about it: the base case is the only place where an answer is actually created from nothing. Every other call only combines answers that came back from below. If the base case is wrong, every answer built on top of it is wrong too.
Choosing the Base Case
Most base cases come from asking one question: what is the smallest input this function should accept, and what is the answer for it? The answer is usually the identity value for the operation you are combining with.
| Problem | Smallest input | Base case value | Why |
|---|---|---|---|
| Sum of a list | `[]` | `0` | Adding 0 changes nothing |
| Product of a list | `[]` | `1` | Multiplying by 1 changes nothing |
| Factorial | `0` | `1` | 0! is defined as 1 |
| Reverse a string | `""` or one character | the string itself | Reversing it gives the same string |
| Count items in a list | `[]` | `0` | An empty list has no items |
| All items satisfy a test | `[]` | `True` | No item fails the test |
Picking the smallest input instead of a slightly larger one makes the function correct for more inputs. Compare these two versions:
def factorial_from_one(n):
if n == 1:
return 1
return n * factorial_from_one(n - 1)
def factorial_from_zero(n):
if n == 0:
return 1
return n * factorial_from_zero(n - 1)
print(factorial_from_zero(0)) # 1
print(factorial_from_one(1)) # 1
# factorial_from_one(0) never reaches n == 1: it calls with -1, -2, -3, ...Both return 120 for 5. Only the second handles 0. Calling factorial_from_one(0) steps past its base case and never comes back.
The Base Case Must Be Reachable
Writing a base case is not enough. Every valid input has to reach it. The base case and the way the input shrinks have to fit together.
A common failure is a base case that uses == while the input moves in steps that can jump over the target value:
def count_down_by_two(n):
if n == 0:
return "done"
return count_down_by_two(n - 2)
print(count_down_by_two(6)) # done
try:
count_down_by_two(5) # 5, 3, 1, -1, -3, ... never equals 0
except RecursionError:
print("RecursionError: the base case was skipped")For even numbers the calls land exactly on 0. For odd numbers they skip it. The fix is to make the base case cover a range of values:
def count_down_by_two(n):
if n <= 0:
return "done"
return count_down_by_two(n - 2)
print(count_down_by_two(5)) # donen <= 0 catches every value that has reached or passed the bottom. This is the safer habit whenever a numeric input could jump past the stopping point or start below it. Factorial benefits from the same treatment. Calling factorial(-3) with an == 0 check never ends. If negative input is a caller mistake, reject it explicitly:
def factorial(n):
if n < 0:
raise ValueError("factorial is not defined for negative numbers")
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120The ValueError check is a guard, not a base case. It stops bad input with a clear error instead of letting it run until Python's recursion limit is hit. A later chapter covers those limits in detail.
Multiple Base Cases
Some functions need more than one base case. This happens when the recursive case reaches back more than one step, or when the input can shrink to more than one smallest shape.
Fibonacci calls itself on n - 1 and n - 2, so it needs answers for both 0 and 1:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55The single test n < 2 covers two base cases at once: fib(0) == 0 and fib(1) == 1. If you wrote only if n == 0: return 0, then fib(1) would call fib(-1) and never stop.
String reversal is similar. It can stop at the empty string or at a single character:
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[0]
print(reverse("abc")) # cba
print(reverse("")) # (empty string)Here len(s) <= 1 covers both shapes. Checking only len(s) == 1 would break on the empty string, because ""[1:] is still "" and the input would never shrink.
Put the Base Case First
Check the base case before doing any work that depends on the input being large enough. Code that runs before the check can fail on the very inputs the base case exists for:
def first_plus_rest_broken(items):
head = items[0] # fails on [] before the base case runs
if not items:
return 0
return head + first_plus_rest_broken(items[1:])
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
print(total([3, 1, 4])) # 8
try:
first_plus_rest_broken([3, 1, 4])
except IndexError:
print("IndexError: indexed an empty list before checking for it")The broken version raises IndexError when it reaches the empty list, because it reads items[0] first. Writing the base case as the first statement, as a guard clause, avoids this whole class of bug.
Common Base Case Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `RecursionError` on every input | No base case at all | Add a direct return for the smallest input |
| `RecursionError` on some inputs | Base case skipped, as with `== 0` and steps of 2 | Use `<=` or cover every terminal shape |
| `RecursionError` on 0 or `[]` | Base case set too high, as with `n == 1` | Lower it to the true smallest input |
| Every answer is off by a factor or offset | Wrong base value, such as `return 0` in a product | Return the identity value |
| `IndexError` or `AttributeError` near the end | Work done before the base case check | Move the check to the top |
Exercises
Exercise
This function should return the number of digits in a non-negative integer, but digits(0) returns 0 instead of 1. Fix the base case so that both digits(0) and digits(12345) are correct.
def digits(n):
if n == 0:
return 0
return 1 + digits(n // 10)
Show answer
Make every single-digit number the base case: if n < 10: return 1. Then digits(0) returns 1, and digits(12345) recurses down through 1234, 123, 12, and 1, returning 5. The original version treated 0 as "no digits left", which is right partway through the recursion but wrong when 0 is the starting input.
Exercise
What base case and value should a recursive product(items) function use, and what goes wrong if it uses if not items: return 0?
Show answer
It should use if not items: return 1, because 1 is the identity for multiplication. Returning 0 makes every product 0, since the last multiplication in each chain is by the base case value. The function does not crash, so this bug is easy to miss.
Exercise
A function halve(n) recurses on n // 2 and has the base case if n == 1: return 0. Which non-negative input never terminates, and how would you fix it?
Show answer
halve(0) never terminates, because 0 // 2 is 0 and the input stops shrinking without ever equaling 1. Change the base case to if n <= 1: return 0, or reject 0 with a guard if it is not valid input.