What this error means

A recursive function (a function that calls itself) went too deep. Python limits recursion depth to prevent infinite loops and stack overflow. The default limit is usually around 1000 calls.

Common causes

  • Missing base case (the condition that stops recursion).
  • Base case never reached (the condition is never true).
  • Recursive call doesn't move toward the base case.

Example that causes the error

def countdown(n):
    print(n)
    countdown(n - 1)  # No base case! Never stops

countdown(5)  # RecursionError: infinite recursion

How to fix it: add a base case

Always have a condition that stops the recursion:

def countdown(n):
    if n <= 0:  # Base case
        print("Done!")
        return
    print(n)
    countdown(n - 1)  # Moves toward base case

countdown(5)  # OK: stops at 0

Make sure recursion moves toward base case

def factorial(n):
    if n <= 1:  # Base case
        return 1
    return n * factorial(n - 1)  # Moves toward 1

result = factorial(5)  # OK: 120

Use iteration instead

For very deep recursion, consider using a loop:

def factorial_iterative(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result  # No recursion limit issues