10.12Recursion
The programme guide includes recursion in this unit. A recursive function solves a problem by calling itself on a smaller version of the same problem. Functions are defined with def (Unit 11 covers functions in detail); here we only need def name(parameters): followed by an indented body, and return to send back a result. The printed unit does not include this material, so this section has no study-material section numbers.
The idea
Every recursive function needs two parts:
- A base case: the simplest input, answered directly (for factorial, 0! = 1).
- A recursive case: the answer expressed in terms of a smaller input (n! = n × (n − 1)!), so that the input moves towards the base case.
How it runs: the call stack
Each call gets its own frame on the call stack, holding its own parameters. Calls wait until the calls they made return.
factorial(3) = 3 * factorial(2) waiting
factorial(2) = 2 * factorial(1) waiting
factorial(1) = 1 * factorial(0) waiting
factorial(0) = 1 base case
factorial(1) = 1 * 1 = 1
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6Recursion versus loops
| Recursion | Loop (iteration) | |
|---|---|---|
| Style | Mirrors problems defined in terms of themselves (trees, factorial, Towers of Hanoi) | Step-by-step repetition |
| Memory | One stack frame per active call | Constant extra memory |
| Limit | Python stops at about 1000 nested calls (RecursionError) | No such limit |
| Speed in Python | Slower (function-call overhead) | Faster |
Python’s default limit can be read with sys.getrecursionlimit() (normally 1000). Python does not optimise tail calls, so very deep recursion should be rewritten as a loop.
Key takeaways
- Recursion = a function calling itself on a smaller problem.
- Base case stops the recursion; recursive case reduces the problem.
- Each call occupies a stack frame; Python’s default limit is about 1000 levels.
- Naive recursion can repeat work; memoisation or a loop fixes it.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a recursive function to compute the sum of the first n natural numbers, and trace it for n = 3.
Show worked answer
def total(n): if n == 1: return 1 and otherwise return n + total(n - 1). Trace: total(3) = 3 + total(2); total(2) = 2 + total(1); total(1) = 1 (base case). Returning: total(2) = 2 + 1 = 3, total(3) = 3 + 3 = 6. The base case n = 1 stops the recursion, and each call reduces n by 1 so it always reaches the base case for n ≥ 1.