Sub topic 1
What Recursion Is: Functions That Call Themselves
A recursive function solves a problem by calling itself on a smaller version of the same problem. This chapter gives you the working model. Later chapters cover each part in detail.
Prerequisites
This chapter assumes you can already:
- Write and call functions in a general-purpose language
- Use conditionals and loops
- Work with basic lists or arrays
- Read simple Python code
The core idea
Many problems contain smaller copies of themselves. The factorial of 5 is 5 * 4 * 3 * 2 * 1, which you can also write as 5 times the factorial of 4. The factorial of 4 is 4 times the factorial of 3, and so on. Once the problem is described in terms of a smaller instance of itself, the code can follow that description directly:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120The function factorial calls factorial. Each call works on a smaller n until it reaches 0. At 0 the function returns an answer without calling itself again.
The two required parts
Every correct recursive function has two parts:
| Part | Role | In `factorial` |
|---|---|---|
| Base case | Returns an answer directly, with no further recursion | `if n == 0: return 1` |
| Recursive case | Calls the function on a smaller input and uses the result | `return n * factorial(n - 1)` |
If the base case is missing, the calls never stop. If the recursive case does not shrink the input, the calls also never stop. In Python, both mistakes end in a RecursionError.
What happens when it runs
Each call waits for the call it makes to return. Then it finishes its own multiplication. The calls go down to the base case first, and the results come back up in reverse order.
The language keeps track of these waiting calls using the call stack. That mechanism has its own chapter.
Common errors at this stage
- Forgetting
returnon the recursive call, so the function returnsNone. - Writing the base case after the recursive call, so it is never reached.
- Choosing a base case the input can skip over, such as testing
n == 0whenndrops by 2 each call.
Exercise
Write a recursive function power(base, exp) that returns base raised to a non-negative integer exp without using ** or loops. Identify its base case and recursive case.
Show answer
def power(base, exp): if exp == 0: return 1; return base power(base, exp - 1). The base case is exp == 0, which returns 1. The recursive case returns base power(base, exp - 1), and each call reduces exp by 1 until it reaches 0. For example, power(2, 3) returns 8.
Exercise
What happens when you call factorial(-1) using the function in this chapter, and why?
Show answer
It raises RecursionError. Starting from -1, n only decreases (-2, -3, ...), so it never equals 0 and the base case is never reached. Python stops the chain of calls once it exceeds the recursion limit.