← Back to Error Lab

RecursionError: maximum recursion depth exceeded

Published 2026-05-01

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

This error occurs when a function calls itself continuously without ever reaching a terminating condition, also known as a base case. Python enforces a maximum recursion depth (default 1000) to prevent infinite loops from consuming all available stack memory, which would crash the interpreter or even the operating system. Common triggers include forgetting to add a return statement that stops the recursion, writing a base-case condition that is never actually satisfied due to incorrect logic, or accidentally passing the wrong arguments in the recursive call so the function never converges toward the base case. Beginners frequently encounter this when implementing algorithms like factorial computation, Fibonacci sequences, or tree traversals without properly reducing the problem size at each step.

Fix / Solution

Implement a proper base case that the recursive function will always eventually reach. Verify that each recursive call moves closer to this base case. If deep recursion is genuinely needed, consider converting the algorithm to an iterative approach using an explicit stack, or increase the limit with sys.setrecursionlimit() — though this should be a last resort.

Code Snippet

import sys

# ❌ Broken — no base case
def factorial_bad(n):
    return n * factorial_bad(n - 1)

# ✅ Fixed — base case stops recursion
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # 120