A function that calls itself
Recursion is what happens when a function calls itself to solve a problem. That sounds a little strange at first - how can a function use itself before it's even finished? The trick is that each call works on a smaller version of the original problem, so the problem eventually shrinks down to something so simple the function can answer immediately.
Think about standing between two mirrors facing each other: you see a reflection of a reflection of a reflection, getting smaller and smaller, forever. A recursive function is like that, except it isn't allowed to go forever - it needs a way to stop.
Every recursive function needs two parts
- The base case - the simple version of the problem that the function can answer directly, without calling itself again. This is what stops the recursion.
- The recursive case - where the function calls itself again, but on a smaller or simpler version of the problem, moving it one step closer to the base case.
Heads up: if you forget the base case - or write one the function can never actually reach - the function will call itself forever. We'll see exactly what that looks like later on this page.
Counting down with recursion
Let's build a function called countdown(n) that prints every number from n down to 0, then prints "Liftoff!".
First, spot the two parts:
- Base case: when n reaches 0, just print "Liftoff!" and stop.
- Recursive case: otherwise, print n, then call countdown again with a smaller number: n - 1.
def countdown(n): if n == 0: print("Liftoff!") else: print(n) countdown(n - 1) countdown(5)
5 4 3 2 1 Liftoff!
Here's what actually happens, one call at a time: countdown(5) prints 5, then calls countdown(4). That call prints 4, then calls countdown(3). This keeps going - countdown(2), countdown(1) - until we reach countdown(0). That's the base case: it prints "Liftoff!" and does not call itself again. No more calls means no more work left to do, so the whole chain finishes.
The call stack: factorial
Countdown didn't need to use the result of the call it made. But a lot of recursive functions do need an answer back before they can finish their own work. The classic example is factorial. The factorial of a number n (written n!) is the product of every whole number from n down to 1. For example, 4! = 4 × 3 × 2 × 1 = 24.
Notice something: 4! = 4 × 3!, and 3! = 3 × 2!, and so on. Factorial is defined in terms of a smaller factorial - a perfect fit for recursion:
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1)
The base case is factorial(0), which is defined to be 1 (there's nothing left to multiply). Every other call is a recursive case: it needs the answer from a smaller call before it can compute its own answer.
Every time a function calls itself, Python remembers where it was so it can come back and finish once the smaller call returns. This "remembering" happens on something called the call stack - a stack of paused calls, each one waiting on the next. Watch what happens when we run factorial(4): the calls pile up going down, then resolve one at a time coming back up.
Calling down
- factorial(4) calls factorial(3)
- factorial(3) calls factorial(2)
- factorial(2) calls factorial(1)
- factorial(1) calls factorial(0)
- factorial(0) is the base case - it just returns 1
Returning up
- factorial(0) = 1
- factorial(1) = 1 × 1 = 1
- factorial(2) = 2 × 1 = 2
- factorial(3) = 3 × 2 = 6
- factorial(4) = 4 × 6 = 24
Each call on the left is stuck waiting for an answer - factorial(3) can't finish until it knows what factorial(2) returns. Only once the base case answers does the stack start unwinding: each waiting call finally gets its number and finishes its own multiplication, from the bottom of the stack back up to the top.
Trace factorial(n) yourself
Pick a number and watch the calls stack up and then unwind, one step at a time - just like the diagram above, but for whatever n you choose.
What happens without a base case?
Look at this broken version of countdown. Can you spot what's missing?
def countdown(n): print(n) countdown(n - 1) # never stops!
There's no base case at all - no condition that ever says "stop here." So countdown(5) calls countdown(4), which calls countdown(3), then countdown(2), countdown(1), countdown(0), countdown(-1), countdown(-2) - and keeps going, since nothing ever tells it to stop.
Python won't let this run forever, though. Every call that's waiting takes up a little bit of space on the call stack, and Python only allows the stack to grow so tall - usually around a thousand calls deep. Once that limit is hit, Python stops the program and raises a RecursionError: maximum recursion depth exceeded. It's not something to be scared of - it's Python protecting your program (and your computer) from a mistake, the same way a stack of plates would eventually topple if you kept adding more.
The fix: every recursive function needs a base case that the recursive case is actually guaranteed to reach. Here, adding back if n == 0: print("Liftoff!") gives the recursion somewhere to stop.
Check yourself
Write a recursive function add_up_to(n) that returns the sum of all the whole numbers from 1 to n. For example, add_up_to(4) should return 10 (because 1 + 2 + 3 + 4 = 10). Try to identify your base case and recursive case before you start typing.
def add_up_to(n): if n == 0: return 0 else: return n + add_up_to(n - 1)
The base case is n == 0, since adding up to 0 is just 0. The recursive case adds n to the sum of everything smaller than it - the same shrink-toward-the-base-case pattern as factorial.
A recursion example
Here's everything from this page in one program: a recursive countdown, factorial, and the sum-up-to function you just tried writing yourself.
Quick quiz
1. What are the two essential parts of every recursive function?
2. What does Python do if a recursive function never reaches its base case?
3. Given this function, what does factorial(3) return?
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1)
Keep learning Python
Recursion is a new way to repeat work, alongside the loops you already know. Brush up on for loops if you want the fundamentals to feel solid, or jump straight into using recursion on real math problems with sequences and series.