RecursionError: maximum recursion depth exceeded
A function kept calling itself without reaching a stopping condition.
What it means
Python caps the call stack at roughly 1000 frames to stop runaway recursion from exhausting memory. Hitting the cap almost always means the base case is missing, unreachable, or the recursive call is not moving toward it.
Common causes
1. No base case
Nothing stops the descent, so it runs until the stack limit.
Breaks
def countdown(n):
print(n)
countdown(n - 1)Works
def countdown(n):
if n <= 0:
return
print(n)
countdown(n - 1)2. The base case can be skipped
Testing == 0 misses it entirely if n starts negative or steps by more than one.
Breaks
def countdown(n):
if n == 0:
return
countdown(n - 2)Works
def countdown(n):
if n <= 0:
return
countdown(n - 2)3. The argument never changes
Recursing with the same value repeats forever.
Breaks
def walk(items):
if not items:
return
walk(items)Works
def walk(items):
if not items:
return
walk(items[1:])How to find it in your own code
Print the argument at the top of the function. If it is not moving toward the base case on every call, that is the bug. Use <= rather than == for the base case so it cannot be stepped over.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.