RecursionError: Maximum Recursion Depth Exceeded

RecursionError: maximum recursion depth exceeded in comparison

Quick Answer

Your function calls itself too many times without reaching a base case. Add or fix the base case, or convert to an iterative approach.

Why This Happens

Python limits recursion depth to 1000 frames by default. When a recursive function lacks a proper base case or input is too large, the stack exceeds this limit.

The Problem

def factorial(n):
    return n * factorial(n - 1)

factorial(5)

The Fix

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

# Or iterative:
def factorial(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

Step-by-Step Fix

  1. 1

    Add a base case

    Every recursive function needs a stopping condition.

  2. 2

    Verify base case is reachable

    Ensure recursive calls move toward the base case.

  3. 3

    Convert to iteration

    Rewrite using a loop or use functools.lru_cache for memoization.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free