Sub topic 3
Factorial: The First Recursive Function
This chapter assumes you can write Python functions, use if statements and for loops, and read Big-O notation. It also builds on the two previous chapters: you should know what a base case and a recursive case are, and have a rough picture of the call stack.
The definition
The factorial of a non-negative integer n, written n!, is the product of all integers from 1 to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. By convention, 0! = 1, which matches the "empty product" of no numbers.
You can also define factorial in terms of itself:
- Base case: 0! = 1
- Recursive case: n! = n × (n − 1)! for n ≥ 1
The recursive case works on a smaller input (n − 1), and each step moves one closer to 0, so the chain always reaches the base case.
The recursive implementation
The code follows the definition line for line:
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(5)) # 120The guard on n < 0 matters. Without it, factorial(-1) would call factorial(-2), then factorial(-3), and so on. It would never reach 0 and would only stop when Python raised a RecursionError.
Tracing a call
Each call has to wait for the call below it to return before it can finish its own multiplication. The calls go down until they reach the base case, and the results then come back up.
The multiplications happen after the recursive calls return, not before. That is why the frames for factorial(3), factorial(2), and factorial(1) all stay on the stack at once.
The iterative implementation
A loop gives the same result by building the product from the bottom up:
def factorial_iter(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_iter(5)) # 120When n is 0 or 1, range(2, n + 1) is empty, so the function returns 1 and the base case is covered without a special branch.
Comparing the two
| Property | `factorial` (recursive) | `factorial_iter` (loop) |
|---|---|---|
| Multiplications | n | n − 1 |
| Time | O(n) | O(n) |
| Extra stack space | O(n) frames | O(1) |
| Matches the math definition | Directly | Indirectly |
| Safe for n = 5000 in CPython | No (default limit is about 1000) | Yes |
Both versions take linear time if you count each multiplication as one step. In practice the numbers grow very large, and Python's arbitrary-precision integers make each multiplication slower as n grows. The stack-space difference is the one that bites first, and a later chapter covers it in detail.
Common errors
- Missing base case: the function recurses until the stack runs out.
- A recursive call that doesn't shrink the input, such as
factorial(n)insidefactorial. - Forgetting
returnon the recursive line. In that case the function returnsNone, and the caller fails with aTypeErrorwhen it tries to multiply.
Exercise
What does this function return for n = 4, and why? def f(n): if n == 0: return 1; n * f(n - 1)
Show answer
It raises a TypeError. f(0) returns 1, but f(1) computes 1 1 and throws the result away, so it implicitly returns None. f(2) then evaluates 2 None, which raises TypeError: unsupported operand type(s). The fix is to write return n * f(n - 1).
Exercise
How many calls to factorial are made when evaluating factorial(6), counting the first call, and what is the maximum number of factorial frames on the stack at once?
Show answer
Seven calls are made: n = 6, 5, 4, 3, 2, 1, 0. All seven are on the stack at the same time when factorial(0) runs, so the maximum depth is 7 frames.