Sub topic 1
What Recursion Is: Functions That Call Themselves
Recursion is a way of solving a problem by having a function call itself on a smaller version of the same problem. This chapter introduces the idea and its vocabulary, then walks through a first example. Later chapters cover each part in detail.
Prerequisites
This chapter assumes you can already do the following:
- Write and call functions in a general-purpose programming language.
- Use conditionals (
if/else) and loops (for,while). - Work with basic lists or arrays.
- Read simple Python code. All examples use Python 3.
You do not need any prior exposure to recursion, data structures beyond lists, or algorithm analysis.
The Core Idea
A recursive function is a function whose body contains a call to itself. That sounds circular, and if written carelessly it is: a function that always calls itself never stops. A working recursive function avoids this by doing two things:
- For some inputs, it returns an answer directly without calling itself. This is the base case.
- For all other inputs, it calls itself on an input that is closer to a base case, then uses that result to build its own answer. This is the recursive case.
The key mental shift is that many problems contain smaller copies of themselves. To compute the factorial of 5, you can multiply 5 by the factorial of 4. To sum a list, you can add the first item to the sum of the rest. When a problem has this self-similar shape, a recursive function can describe the solution in a few lines that mirror the definition of the problem.
A First Example: Factorial
The factorial of a non-negative integer n, written n!, is the product of all integers from 1 to n. By convention, 0! = 1. Mathematicians often define it like this:
0! = 1n! = n × (n − 1)!forn > 0
That definition refers to factorial inside its own definition, so it translates almost word for word into code:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120Here are the two required parts in this function:
| Part | Code | Role |
|---|---|---|
| Base case | `if n == 0: return 1` | Stops the recursion with a known answer |
| Recursive case | `return n * factorial(n - 1)` | Reduces the problem and combines the result |
Each call passes n - 1, so the argument shrinks by one every time. Starting from any non-negative integer, it eventually reaches 0, the base case returns 1, and the waiting calls finish their multiplications.
Unfolding the Calls
To see what happens, expand factorial(3) by hand, replacing each call with its definition:
factorial(3)
= 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0)))
= 3 * (2 * (1 * 1))
= 6The work happens in two phases. On the way down, each call is waiting for the result of a smaller call. On the way back up, each waiting call receives a value and finishes its multiplication.
Each active call has its own separate copy of n. When factorial(2) is running, its n is 2, and the caller's n is still 3. The language keeps these copies apart using the call stack, which gets its own chapter later in this tutorial.
Recursion Is Not Special Syntax
Python has no keyword for recursion. A recursive call is an ordinary function call that happens to name the function currently running. The interpreter handles it the same way it handles a call to print or len: it pauses the caller, runs the callee with fresh local variables, and resumes the caller when the callee returns.
This matters because it removes the mystery. If you understand how function calls work, you already understand the mechanism of recursion. The new skill is designing functions so that the chain of calls is guaranteed to end with a correct answer.
Two Ways a Recursive Function Goes Wrong
Most early recursion bugs fall into one of two categories.
Missing or unreachable base case
If there is no base case, or the inputs can never reach it, the function calls itself until Python stops it:
def broken_factorial(n):
return n * broken_factorial(n - 1)
try:
broken_factorial(5)
except RecursionError as e:
print("RecursionError:", e)The same failure happens with the correct factorial if you pass a negative number. factorial(-1) calls factorial(-2), and the argument moves away from 0 forever.
Recursive call that does not shrink the problem
If the recursive call uses the same input, for example factorial(n) instead of factorial(n - 1), the function makes no progress and fails the same way. Every recursive call must work on a strictly smaller problem, where "smaller" means some measure that is guaranteed to bottom out, such as a non-negative integer counting down, a list getting shorter, or a tree getting shallower.
A Second Example: Summing 1 to n
The same pattern applies to many problems. Here is the sum of the integers from 1 to n:
def sum_to(n):
if n <= 0:
return 0
return n + sum_to(n - 1)
print(sum_to(4)) # 10
print(sum_to(-3)) # 0Using n <= 0 instead of n == 0 as the base case makes the function safe for negative inputs as well. Widening a base case like this is a common defensive technique.
Where Recursion Shows Up
Recursion is most natural when the data or the problem is defined in terms of itself:
- Mathematical definitions such as factorial, Fibonacci numbers, and powers.
- Sequences such as lists and strings, which split into a first element and a shorter remainder.
- Hierarchical data such as file systems, HTML documents, organization charts, and binary trees, where each node contains smaller structures of the same kind.
- Search problems such as generating permutations or solving puzzles, where each choice leaves a smaller problem.
- Divide-and-conquer algorithms such as merge sort, which split the input, solve each part, and combine the results.
Any recursive function can be rewritten with loops, and later chapters compare the two styles and show how to convert between them. For self-similar problems, though, the recursive version is often shorter and closer to the problem's definition.
Exercises
Exercise
Write a recursive function power(base, exp) that returns base raised to the non-negative integer exp, without using ** or pow. 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 multiplies base by power(base, exp - 1), and exp shrinks by one on each call, so it reaches 0.
Exercise
Why does factorial(-1) never finish when using the factorial function from this chapter, and what is the smallest change that fixes it?
Show answer
The base case checks n == 0, but starting from -1 each call subtracts 1, so n goes -2, -3, and so on and never equals 0. Python eventually raises RecursionError. Changing the condition to n <= 0 makes negative inputs hit the base case (returning 1). Raising a ValueError for n < 0 also works and is stricter.
Exercise
Expand sum_to(3) by hand in the same style as the factorial(3) expansion, showing each substitution until you reach the final value.
Show answer
sumto(3) = 3 + sumto(2) = 3 + (2 + sumto(1)) = 3 + (2 + (1 + sumto(0))) = 3 + (2 + (1 + 0)) = 6.