Python Recursion
A function is recursive when it calls itself. Recursion is a natural fit for problems that contain smaller copies of themselves: folders inside folders, a family tree, or a maths definition like "n! = n × (n−1)!".
The two essential parts
Every recursive function needs:
- a base case — a simple input it can answer directly, without recursing;
- a recursive case — a step that calls the function on a smaller input, moving toward the base case.
def countdown(n):
if n == 0: # base case
print("Liftoff!")
return
print(n)
countdown(n - 1) # recursive case: a smaller problem
countdown(3)3
2
1
Liftoff!
Factorial
The factorial of n (written n!) is n × (n−1) × … × 1, with 0! = 1. The definition translates directly into code:
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
for n in [0, 1, 5, 10]:
print(f"{n}! = {factorial(n)}")0! = 1
1! = 1
5! = 120
10! = 3628800
How factorial(4) unfolds:
| Call | Waits for | Returns |
|---|---|---|
factorial(4) |
4 * factorial(3) |
24 |
factorial(3) |
3 * factorial(2) |
6 |
factorial(2) |
2 * factorial(1) |
2 |
factorial(1) |
— base case | 1 |
Each call waits on the call stack until the one below it returns, then finishes its own multiplication.
Recursion on nested data
Recursion is most valuable when data is nested to an unknown depth. Here we add up every number in a list that may contain lists, which may contain lists…
def deep_sum(items):
total = 0
for item in items:
if isinstance(item, list):
total += deep_sum(item) # recurse into the sub-list
else:
total += item
return total
data = [1, [2, 3], [4, [5, [6]]], 7]
print(deep_sum(data))28
The same shape of code walks folder trees, menus, JSON documents and HTML.
The recursion limit
Every pending call uses memory. To protect itself from runaway recursion, Python stops at a limit (usually around 1000 levels; sys.getrecursionlimit() tells you the exact value) and raises RecursionError:
def forever(n):
return forever(n + 1) # no base case!
try:
forever(0)
except RecursionError as err:
print("RecursionError:", err)RecursionError: maximum recursion depth exceeded
Tip: Python does not optimise tail calls. For a simple loop-like process over thousands of items, a normal
fororwhileloop is the better choice.
Fibonacci and memoisation
The Fibonacci sequence (0, 1, 1, 2, 3, 5, 8, …) is defined recursively: each number is the sum of the two before it. The naive version recomputes the same values again and again and becomes very slow for larger n. Caching results with functools.lru_cache fixes that:
from functools import lru_cache
calls = 0
def fib_slow(n):
global calls
calls += 1
if n < 2:
return n
return fib_slow(n - 1) + fib_slow(n - 2)
print(fib_slow(20), "after", calls, "calls")
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(20))
print(fib(100))6765 after 21891 calls
6765
354224848179261915075
The @lru_cache line is a decorator — you'll learn how those work in the Decorators lesson.
Recursion vs loops
| Recursion | Loop | |
|---|---|---|
| Best for | trees, nested data, divide-and-conquer | flat sequences, simple repetition |
| Memory | one stack frame per level | constant |
| Readability | mirrors recursive definitions | mirrors step-by-step processes |
Test yourself
What happens if a recursive function has no base case?
- It returns None
- It loops forever silently
- It eventually raises RecursionError
- Python adds a base case automatically
In factorial, what is the purpose of if n <= 1: return 1?
- It's the recursive case
- It's the base case that stops the recursion
- It speeds up the function
- It handles negative numbers only