Sub topic 2
Recursion: Base Cases and Recursive Cases
This chapter assumes you can write and call Python functions, use for and while loops, and work with lists and strings. It covers how a recursive function is put together and the mistakes that most often break one. Later chapters cover the call stack, step-by-step tracing, and depth limits in detail. Here, the goal is to read and write recursive functions correctly.
What Makes a Function Recursive
A recursive function is a function that calls itself. Every working recursive function has two parts:
- A base case is an input simple enough that the function returns an answer directly, without calling itself.
- A recursive case handles every other input. It reduces the problem to a smaller version of itself, calls the function on that smaller version, and builds its own answer from the result.
The recursive case must move the input closer to a base case on every call. If it doesn't, the calls never stop. This third requirement is easy to miss, so treat it as part of the definition. A recursive function is correct when its base cases are right, its recursive case combines results correctly, and every chain of calls reaches a base case.
Factorial Both Ways
The factorial of n, written n!, is the product 1 × 2 × ... × n, with 0! = 1. It has a natural recursive definition: 0! = 1, and n! = n × (n - 1)! for n > 0. The code follows the definition line for line.
def factorial_recursive(n):
if n == 0:
return 1
return n * factorial_recursive(n - 1)
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_recursive(5)) # 120
print(factorial_iterative(5)) # 120In factorial_recursive, the base case is n == 0, which returns 1. The recursive case is n * factorial_recursive(n - 1). Each call subtracts 1 from n, so any non-negative starting value eventually reaches 0.
The two versions line up closely:
| Role | Recursive version | Iterative version |
|---|---|---|
| Starting value | Base case returns `1` | `result = 1` before the loop |
| Update step | `n * (result of smaller call)` | `result *= i` |
| Progress | `n - 1` in the argument | `i` advances through `range` |
| Stopping condition | `n == 0` | `range` runs out |
The base case plays the part of the loop's initial value, and the recursive case plays the part of the loop's update step. The order differs, though. The loop multiplies from small numbers up. The recursion waits until it reaches the bottom and then does its multiplications as the calls return. The chapter on the call stack explains where those pending multiplications are stored.
Writing a Recursive Function: A Recipe
Use these steps when you write a recursive function:
- Find the smallest inputs whose answers are obvious, such as an empty list,
n == 0, or a one-character string. These are your base cases. - Pick a way to shrink the input: drop the first element, subtract 1, halve a number, or take a subtree.
- Assume the recursive call already works on the smaller input. Don't trace it in your head. Ask only: "If I had the answer for the smaller input, how would I build the answer for this one?"
- Check that every path ends in a base case, including unusual inputs such as negative numbers or odd lengths.
Step 3 is sometimes called the "recursive leap of faith." It is the same reasoning as a proof by induction: if the base case is correct, and each step is correct whenever the smaller step is, then the whole function is correct.
More Than One Base Case
Many functions need several base cases, and some base cases exist to stop early rather than because the input is small. A palindrome check shows both:
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome("racecar")) # True
print(is_palindrome("abba")) # True
print(is_palindrome("abca")) # False
print(is_palindrome("")) # TrueThe test len(s) <= 1 covers both empty strings and one-character strings. That matters because each call removes two characters. Strings of even length end at length 0 and strings of odd length end at length 1. If the test were len(s) == 0, every odd-length palindrome would skip past it. The slicing would then keep producing empty strings and never stop. The mismatch test is a second base case that returns False as soon as the outer characters differ.
Shrinking Faster Than by One
Progress doesn't have to mean subtracting 1. This power function halves the exponent on each call, so it needs about log₂(n) calls instead of n:
def power(x, n):
if n == 0:
return 1
half = power(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
print(power(2, 10)) # 1024
print(power(3, 5)) # 243For n = 5, the calls go 5 → 2 → 1 → 0. Integer division always reduces a positive n, so the base case n == 0 is always reached. The function also stores power(x, n // 2) in half and reuses it. Writing power(x, n // 2) * power(x, n // 2) would make two recursive calls per level and throw away the speedup. The chapter on multiple recursion looks at that kind of repeated work.
Common Errors
Most broken recursive functions fail in one of a few ways.
| Error | Symptom | Fix |
|---|---|---|
| No base case | `RecursionError` on every input | Add a direct return for the smallest input |
| Base case never reached | `RecursionError` on some inputs (negatives, odd lengths) | Widen the base case or validate input |
| Input doesn't shrink | `RecursionError` everywhere | Make sure the argument changes toward the base case |
| Forgot `return` on the recursive call | `None` appears, or a `TypeError` | Return the recursive result |
| Wrong base value | Answer is off by a constant or factor | Check the base case against the definition |
The missing return is especially confusing because the base case works and the error shows up one level higher:
def sum_list_buggy(items):
if not items:
return 0
items[0] + sum_list_buggy(items[1:]) # result is computed, then discarded
def sum_list(items):
if not items:
return 0
return items[0] + sum_list(items[1:])
try:
print(sum_list_buggy([1, 2, 3]))
except TypeError as e:
print("TypeError:", e)
print(sum_list([1, 2, 3])) # 6In the buggy version, the call on [3] computes 3 + 0 and then falls off the end of the function, so it returns None. The call on [2, 3] then tries 2 + None and raises TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'.
A base case that some inputs never reach is just as common. factorial_recursive(-1) calls itself with -2, -3, and so on, and never hits 0. Python eventually raises RecursionError. Guard against it at the boundary:
def factorial(n):
if n < 0:
raise ValueError("factorial is undefined for negative numbers")
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
try:
factorial(-1)
except ValueError as e:
print("ValueError:", e)Exercises
Exercise
In the function below, name the base case(s) and the recursive case, and state how the input moves toward a base case. def countdigits(n): if n < 10: return 1 return 1 + countdigits(n // 10)
Show answer
The base case is n < 10, which returns 1 because a single-digit number has one digit. The recursive case is 1 + count_digits(n // 10). It counts the last digit and recurses on the number with that digit removed. Integer division by 10 makes a non-negative n strictly smaller until it drops below 10. A negative n is already below 10, so the function returns 1 immediately, which is wrong for numbers like -42. Fix it by taking abs(n) first.
Exercise
This function should return the sum of the even numbers from n down to 0 when n is even. Calling it with an odd n raises RecursionError. Explain why and fix it. def sumevens(n): if n == 0: return 0 return n + sumevens(n - 2)
Show answer
An odd n goes n, n-2, ..., 1, -1, -3, ... and skips 0, so the base case is never reached. Change the base case to "if n <= 0: return 0". To handle odd inputs correctly as well, start from the largest even number not above n: "if n % 2 == 1: return sum_evens(n - 1)" before the general recursive case.
Exercise
Write a recursive function reverse(s) that returns the string s reversed. State your base case and how each call shrinks the input.
Show answer
def reverse(s): if len(s) <= 1: return s return reverse(s[1:]) + s[0] The base case is a string of length 0 or 1, which is its own reverse. Each call removes the first character, reverses the rest, and appends the removed character at the end. For example, reverse("abc") returns "cba".