Sub topic 1
What Makes a Function Recursive
A recursive function is a function that calls itself to solve a smaller version of the same problem. That sounds circular, but it works when each call moves toward a case simple enough to answer directly. This chapter covers the two parts every recursive function needs, how to check that a recursive definition actually finishes, and the mistakes that most often break recursive code. Later chapters look at how the computer runs these calls and how to make them efficient.
Prerequisites
This chapter assumes you can already:
- Write and call functions in Python, including functions that return values.
- Use conditionals (
if/else) and loops. - Use integer division (
//) and remainder (%). - Read Big-O notation such as O(n) and O(log n). It comes up briefly here and much more in later chapters.
You do not need to know anything about the call stack yet. The next chapter covers it.
The two parts of every recursive function
Every correct recursive function has two kinds of branches:
- Base case: an input small enough that the function returns an answer directly, with no further self-calls.
- Recursive case: an input that the function handles by calling itself on a smaller input, then using that result to build its own answer.
Here is a small example. It adds up the numbers in a list:
def sum_list(items):
if not items: # base case: empty list
return 0
return items[0] + sum_list(items[1:]) # recursive case
print(sum_list([4, 7, 1, 8])) # 20
print(sum_list([])) # 0The base case is the empty list, whose sum is 0 by definition. The recursive case says that the sum of a non-empty list is its first element plus the sum of the rest. Each call passes a list that is one element shorter, so the calls eventually reach the empty list and stop.
The function never loops over the list. It relies on one fact: if sum_list works on shorter lists, adding the first element gives the correct sum for this list. Chapter 4 turns this idea into a proof by induction.
Recursive definitions come from mathematics
Many recursive functions are direct translations of recursive mathematical definitions. The three problems in this tutorial are all defined this way:
| Problem | Base case(s) | Recursive case | What shrinks |
|---|---|---|---|
| Factorial | 0! = 1 | n! = n × (n − 1)! | n decreases by 1 |
| Fibonacci | F(0) = 0, F(1) = 1 | F(n) = F(n − 1) + F(n − 2) | n decreases by 1 and by 2 |
| Power | x⁰ = 1 | xⁿ = x × xⁿ⁻¹ | n decreases by 1 |
| Sum of list | sum([]) = 0 | sum(L) = L[0] + sum(L[1:]) | length decreases by 1 |
Two points in this table are worth noticing.
First, a function can have more than one base case. Fibonacci needs two, because its recursive case reaches back two steps. If you supplied only F(0), computing F(1) would call F(0) and F(−1), and F(−1) never reaches a base case.
Second, the thing that shrinks is not always the input itself. In sum_list the list changes, but what shrinks is its length. Being able to name this measure is the main tool for checking that a recursive function finishes.
Termination: the measure must reach a base case
A recursive function finishes on an input only if every chain of calls from that input reaches a base case. The usual way to check this:
- Pick a measure, a non-negative whole number computed from the input (a value of n, a list length, a number of digits).
- Check that every recursive call is made on an input with a strictly smaller measure.
- Check that every input at the smallest measure values is handled by a base case.
A non-negative integer cannot decrease forever, so the chain of calls must stop. Here is the method applied to a function that adds the digits of a non-negative integer:
def sum_digits(n):
if n < 0:
raise ValueError("n must be non-negative")
if n < 10: # base case: a single digit
return n
return n % 10 + sum_digits(n // 10) # last digit + sum of the rest
print(sum_digits(9045)) # 18
print(sum_digits(7)) # 7The measure is the number of digits. n // 10 removes the last digit, so each call has one fewer digit. Every single-digit number (0 through 9) is caught by the base case n < 10, so the chain always ends. The guard for negative input matters. Without it, Python's floor division would map −5 to −1, and −1 // 10 is −1 again, so if the base case were written differently the function could recurse forever on negative input.
Structural and generative recursion
Recursive functions usually shrink their input in one of two ways.
- Structural recursion follows the shape of the data or the definition: remove one element, subtract 1 from n, remove one digit.
sum_list,sum_digits, and factorial are structural. Termination is usually obvious. - Generative recursion builds a new, smaller subproblem by some computation, such as halving the exponent. Exponentiation by squaring (Chapter 12) works this way: it computes xⁿ from x^(n // 2). The measure is still n, but it shrinks much faster, which is where the speed-up comes from. Termination needs more care, because you have to check that the computation really makes the measure smaller every time. For example, n // 2 is smaller than n only when n ≥ 1, so n = 0 must be a base case.
Common errors
The same few mistakes cause most broken recursive functions. All of the examples below run, and they catch their errors so you can see what Python reports.
Missing base case
def bad_sum(items):
return items[0] + bad_sum(items[1:]) # no base case
try:
bad_sum([1, 2, 3])
except IndexError as e:
print("IndexError:", e) # IndexError: list index out of rangeYou might expect infinite recursion here, but the function fails differently. It keeps going until the list is empty and then crashes on items[0]. A missing base case often shows up as an error deep in the recursion instead of a clear "never stops." If you see an error on the smallest possible input, check the base case first.
No progress toward the base case
def stuck(n):
if n == 0:
return 0
return stuck(n) # same input: the measure never shrinks
try:
stuck(3)
except RecursionError as e:
print("RecursionError:", e) # maximum recursion depth exceededThe base case exists, but the recursive call passes the same input, so it is never reached. Python stops after about 1000 nested calls by default and raises RecursionError. Chapter 5 explains this limit.
Progress in the wrong direction, or skipping the base case
def countdown(n):
if n == 0:
return ["liftoff"]
return [n] + countdown(n - 1)
print(countdown(3)) # [3, 2, 1, 'liftoff']
try:
countdown(-1) # -1, -2, -3, ... never hits 0
except RecursionError:
print("RecursionError on negative input")For positive n the function works. For negative n, subtracting 1 moves away from 0, so the base case is never reached. You can fix this in two ways: reject invalid input with a ValueError, or widen the base case to n <= 0. Choose whichever matches the meaning of the function. The aim is that every valid input reaches a base case and every invalid input is rejected early.
Base case returns the wrong value
def product_list(items):
if not items:
return 0 # wrong: should be 1
return items[0] * product_list(items[1:])
print(product_list([2, 3, 4])) # 0, not 24This version terminates but always gives the wrong answer, because every product ends by multiplying by 0. The base case has to be the identity for the combining operation: 0 for addition, 1 for multiplication, an empty list for list concatenation. The same reasoning explains why 0! = 1 and x⁰ = 1.
Forgetting to use or return the recursive result
def sum_list_broken(items):
if not items:
return 0
items[0] + sum_list_broken(items[1:]) # result computed, then discarded
print(sum_list_broken([1, 2, 3])) # NoneWithout return, the recursive case falls off the end of the function and returns None. This mistake is easy to make when you translate a mathematical definition into code.
A design checklist
When you face a new problem, work through these questions in order:
- What is the smallest input? Its answer becomes the base case. Check whether you need more than one.
- How can a bigger input be expressed in terms of a smaller one? That gives the recursive case.
- How do you combine the smaller answer with local work? Make sure the base case returns the identity for that combination.
- What is the measure, and does every call shrink it? Check that invalid inputs, such as negative numbers, cannot get around the base case.
- Do you return the combined result on every path?
The rest of this tutorial applies this checklist to factorial, Fibonacci, and powers. It also covers what the computer does with all these calls, and when the direct recursive version is too slow or too deep to use.
Exercise
Write a recursive function count_down_evens(n) that returns a list of the even numbers from n down to 0 (inclusive) for any non-negative even integer n, for example count_down_evens(6) returns [6, 4, 2, 0]. Name its base case, its recursive case, and its measure. What happens if someone calls it with n = 5, and how would you fix that?
Show answer
One solution: if n == 0: return [0] as the base case, and return [n] + count_down_evens(n - 2) as the recursive case. The measure is n, which decreases by 2 on each call. With n = 5 the calls go 5, 3, 1, -1, -3, ..., skipping 0, so the function recurses until it raises RecursionError. To fix it, validate the input (if n < 0 or n % 2 != 0: raise ValueError(...)) or widen the base case to if n <= 0: return [0] if n == 0 else [].
Exercise
A student writes def length(s): if s == "": return 1 followed by return 1 + length(s[1:]) to compute the length of a string. Does it terminate? Is it correct? Explain using the idea of the identity value.
Show answer
It terminates, because each call removes one character and the empty string is caught by the base case. It is not correct: it returns one more than the true length (length("ab") gives 3). The combining operation is addition, whose identity is 0, so the base case should return 0 for the empty string.
Exercise
Fibonacci is defined by F(n) = F(n-1) + F(n-2). Explain why a single base case F(0) = 0 is not enough, and say which base cases are required.
Show answer
The recursive case reaches back two steps. Computing F(1) with only F(0) defined would call F(0) and F(-1), and F(-1) calls F(-2) and F(-3), so the calls move away from 0 and never reach a base case. Both F(0) = 0 and F(1) = 1 are needed, so that every n ≥ 2 reduces to inputs of 0 or 1.