Python RecursionError: meaning and fix

RecursionError: A function called itself too many times.

Code that causes it

def f(n):
    return f(n + 1)

f(0)
Open in the runner

There is no stopping condition. There is one, but the value never gets closer to it.

Write the stopping condition at the top of the function. Check that each call moves closer to it.

How to fix it

def f(n):
    if n >= 5:
        return n
    return f(n + 1)

print(f(0))
Open in the runner

Why it happens

Python stacks only about a thousand calls. A call chain with no end stops before that.

The official docs are in English. See it in the official Python docs

Back to the runnerMore errors