RecursionError: maximum recursion depth exceeded
A function kept calling itself and never stopped. Python stops it after about 1,000 calls.
Your error
Check these first
- A base case. A recursive function needs a case that returns without calling itself again.
- Getting closer. Each call has to move towards that case: a smaller number, a shorter list.
- Can it be skipped?
if n == 0is never true whenngoes 5, 3, 1, -1. Compare with<=instead.
Causes and fixes
1 No base case
Without a case that stops it, the function calls itself until Python stops it. Add one, usually at the top.
def factorial(n):
return n * factorial(n - 1)
print(factorial(5))
RecursionError: maximum recursion depth exceeded
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
120
2 A base case that's never reached
Counting down by 2 from 5 jumps over 0, so n == 0 is never true. A check with <= catches every way past it.
def countdown(n):
if n == 0:
return
print(n)
countdown(n - 2)
countdown(5)
RecursionError: maximum recursion depth exceeded
def countdown(n):
if n <= 0:
return
print(n)
countdown(n - 2)
countdown(5)
5 3 1
Still stuck?
- In the traceback,
File "main.py", line 3says where the error happened. In the editor, click that line to go to it. - Go over the basics: Recursion
- Other errors: AttributeError, FileNotFoundError, IndentationError, IndexError, KeyError, ModuleNotFoundError, NameError, SyntaxError, TypeError, UnboundLocalError, ValueError, ZeroDivisionError