Python error explained
RecursionError: what it means and how to fix it
A function kept calling itself and never stopped.
The message
RecursionError: maximum recursion depth exceeded
What it means
A recursive function calls itself on a smaller problem until it reaches a base case that returns without recursing. Without a base case, or if the problem never gets smaller, it would go on for ever, so Python stops it after about 1,000 calls.
Common causes
- A missing base case
- A base case that is never reached, like checking n == 0 when n goes negative
- Calling the function with the same argument instead of a smaller one
Example that raises it
def countdown(n):
print(n)
countdown(n - 1)
countdown(3)
The fix
def countdown(n):
if n == 0:
print("Lift off!")
return
print(n)
countdown(n - 1)
countdown(3)
Tip: Write the base case first. Make sure every recursive call moves closer to it.
Fix the broken version yourself in the editor on this page. It runs real Python in your browser.