Sub topic 3
Factorial: The First Recursive Function
This chapter assumes you can write and call Python functions, use if statements and for loops, and read Big-O notation. It also builds on the two previous chapters. From the first, you need the idea of a base case and a recursive case. From the second, you need the picture of the call stack as a pile of stack frames, one per active call.
Factorial is the standard first example of recursion. Its mathematical definition already has a recursive shape, so the code reads almost like the math. That makes it a good place to see the whole recursive pattern work before the harder problems later in the tutorial.
The Definition
For a non-negative integer n, the factorial n! is the product of all integers from 1 to n:
- 5! = 5 × 4 × 3 × 2 × 1 = 120
- 1! = 1
- 0! = 1
The product form hides a useful fact: every factorial contains the factorial just below it. 5! = 5 × (4 × 3 × 2 × 1) = 5 × 4!. Written as a recurrence, this gives two rules:
- Base case: 0! = 1
- Recursive case: n! = n × (n − 1)! for n ≥ 1
Why 0! equals 1
Beginners often find 0! = 1 strange, but it follows from two arguments. First, 0! is the product of no numbers. The empty product is 1, the identity for multiplication, in the same way that an empty sum is 0. Second, the recurrence demands it. Setting n = 1 gives 1! = 1 × 0!, and since 1! is 1, 0! has to be 1.
This matters for code. If you choose 0 as the base case, the function works for every non-negative integer, 0 included.
Translating the Definition into Code
Each rule in the recurrence becomes one branch of the function:
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 function is short, and each line has a job:
| Line | Role |
|---|---|
| `if n < 0: raise ValueError(...)` | Rejects input the definition does not cover |
| `if n == 0: return 1` | Base case: answers directly with no further calls |
| `return n * factorial(n - 1)` | Recursive case: shrinks the problem by 1 and combines the result |
Each recursive call passes n - 1, so the argument moves toward 0 by one step per call. Starting from any non-negative integer, it reaches 0 in exactly n steps. That guaranteed progress toward the base case is why the function terminates.
Tracing a Call
The multiplication in the recursive case cannot run until the inner call returns. So the computation runs in two phases. In the winding phase, calls pile up on the stack. In the unwinding phase, results come back down and get multiplied in.
The traced version below prints each call and each return, indented by depth:
def factorial_traced(n, depth=0):
indent = " " * depth
print(f"{indent}factorial({n})")
if n == 0:
print(f"{indent}return 1")
return 1
result = n * factorial_traced(n - 1, depth + 1)
print(f"{indent}return {result}")
return result
factorial_traced(3)Output:
factorial(3)
factorial(2)
factorial(1)
factorial(0)
return 1
return 1
return 2
return 6Read it top to bottom. Each indented line is a new stack frame. No multiplication happens until factorial(0) returns 1. After that, each frame multiplies its own n by the value it received: 1 × 1 = 1, then 2 × 1 = 2, then 3 × 2 = 6.
At the deepest point, n + 1 frames are active at once: one each for factorial(n) down to factorial(0). The space cost is therefore O(n), on top of the O(n) multiplications. This linear stack growth will matter in the chapter on recursion depth limits.
The Iterative Version
The same product can be built with a loop that multiplies up from 2:
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 loop body never runs and the function returns 1. The starting value result = 1 plays the role of the base case. It is the empty product again.
The two versions compute the same values, but they use resources differently:
| Property | Recursive `factorial` | Iterative `factorial_iter` |
|---|---|---|
| Multiplications for input n | n (includes 1 × 1) | n − 1 for n ≥ 2 |
| Extra stack frames | n + 1 | 1 |
| Largest n with default CPython settings | a little under 1000 | limited only by memory and time |
| Closeness to the math definition | direct | a step removed |
| Rejects negative input | yes | no, silently returns 1 |
The last row is a real difference. factorial_iter(-3) returns 1 because range(2, -2) is empty. If negative input can reach this function, add the same ValueError check that the recursive version has.
Checking the two against each other
When you have two implementations of the same function, test them against each other and against a trusted reference. Python's standard library has math.factorial:
import math
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial(n - 1)
def factorial_iter(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
for n in range(50):
assert factorial(n) == factorial_iter(n) == math.factorial(n)
print("all match")Edge Cases
Very large results
Factorials grow faster than exponentials. 20! is about 2.4 × 10¹⁸, which is close to the 64-bit signed integer maximum of about 9.2 × 10¹⁸. 21! exceeds it. In C or Java with fixed-width integers, 21! silently overflows. Python integers have arbitrary precision, so factorial_iter(100) returns all 158 digits exactly. The cost is that each multiplication gets slower as the numbers grow, so for large n the O(n) count of multiplications understates the real running time.
Deep recursion
CPython's default recursion limit is 1000 frames. Calling factorial(1000) needs 1001 frames of its own on top of the caller's frame, so it raises RecursionError, while factorial_iter(1000) returns without trouble. A later chapter covers why the limit exists and how to work around it.
Non-integer input
The definition covers non-negative integers only, but the recursive code does not check types. Watch what factorial(2.5) does: it calls itself with 1.5, then 0.5, then -0.5, and finally raises ValueError("n must be non-negative"). The error is raised, but the message points at the wrong problem. A float that never lands exactly on 0, such as 0.1 added up repeatedly, behaves the same way. To reject floats directly, add a type check:
def factorial_strict(n):
if not isinstance(n, int) or isinstance(n, bool):
raise TypeError("n must be an int")
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial_strict(n - 1)
print(factorial_strict(6)) # 720The bool exclusion is needed because True is an int in Python, so without it factorial_strict(True) would return 1.
Common Mistakes
Other errors that come up often:
- Forgetting
returnbefore the recursive expression. Writingn * factorial(n - 1)withoutreturnmakes the function returnNone, and the caller then fails withTypeError: unsupported operand type(s) for *: 'int' and 'NoneType'. - Recursing on
ninstead ofn - 1. The argument never shrinks, so the call recurses until it hits the limit. - Writing
range(1, n)in the loop. It drops the final factor, so the loop computes (n − 1)! instead of n!. - Starting the accumulator at 0 instead of 1. Every product then comes out 0.
The next chapter shows how to argue that the recursive version is correct for every n, using induction to prove what the tests here only sample.
Exercise
How many multiplications does the recursive factorial(n) perform for n ≥ 1, and how many does factorial_iter(n) perform for n ≥ 2? Explain the difference.
Show answer
The recursive version performs n multiplications, one in each frame from n down to 1. The frame for n = 1 computes 1 factorial(0) = 1 1. The iterative version performs n − 1, because its loop starts at 2 and the trivial multiplication by 1 is folded into the starting value result = 1.
Exercise
A colleague writes a base case of if n <= 1: return 1 and no negative check. What does their function return for n = 0, n = 1, and n = -4, and is that a problem?
Show answer
It returns 1 for all three. The results for 0 and 1 are correct, and the function always terminates. Returning 1 for -4 is a silent wrong answer, because factorial is undefined for negative integers. Add an explicit check that raises ValueError for negative n.
Exercise
The double factorial n!! is the product of every second integer from n down to 1 or 2, with 0!! = 1 and 1!! = 1. For example, 7!! = 7 × 5 × 3 × 1 = 105. Write it recursively.
Show answer
def doublefactorial(n): return 1 if n <= 1 else n * doublefactorial(n - 2). It needs two base values because subtracting 2 reaches 0 from even n and 1 from odd n. Add a check that rejects n < 0 if negative input is possible.