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)

RecursionError: maximum recursion depth exceeded

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: Functions

Frequently 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.