All Python errors
RecursionError in Python: maximum recursion depth exceeded
RecursionError means a function called itself too many times, usually because it never stops. To fix it, add a stopping condition (a base case) and make every new call move closer to it.
Code with the error
def main():
def add_up(n):
return n + add_up(n - 1)
print(add_up(4))
main()
Error message (Python 3.12, last line)
Corrected code
def main():
def add_up(n):
if n <= 0:
return 0
return n + add_up(n - 1)
print(add_up(4))
main()
Output
10
Common causes
- There is no base case.
- The argument does not change, so the base case is never reached.
- The condition is skipped: n == 0 never happens if n starts below zero.
- The task is too deep for recursion; a loop works better.
Practise in the course
Lesson: FunctionsFrequently asked questions
What is the recursion limit in Python?
About 1000 nested calls by default.
Why is the function in the example inside main()?
In the editor on this site a function that calls itself has to be defined inside another function. In ordinary Python it also works at the top level.