Base Cases
And when recursion goes wrong.
The most common recursion bug is a missing or wrong base case. The function calls itself forever, the call stack fills up, and Python stops with an error. Let's see it happen, so you'll recognise it.

- Missing base case
- The stack fills up
- Python stops with an error
Forgetting the base case
This version of countdown has no base case. It just keeps calling itself, with smaller and smaller numbers, into the negatives. Run it. After about a thousand calls, Python gives up with a recursion error. Maximum recursion depth exceeded.
def countdown(n):
print(n, end=" ") if n > 997 else None
countdown(n - 1)
try:
countdown(1000)
except RecursionError as e:
print("\nRecursionError:", e)1000 999 998 RecursionError: maximum recursion depth exceeded
Writing good base cases
Always write the base case first, before the recursive call. Make sure every call moves closer to it, usually by making the input smaller. Check the edge cases, like zero, one, or an empty list. And if the depth could be huge, like a million, use a loop instead.
| key | value |
|---|---|
| Base case first | at the top |
| Move closer | smaller input every call |
| Edge cases | 0, 1, empty |
| Very deep? | use a loop |
Summary
A missing base case causes a recursion error. Write the base case first, and make every call move towards it. Next, recursion practice.
Key takeaways- Base case first
- Always get smaller
- RecursionError = no way out