How to Fix: RecursionError: maximum recursion depth exceeded

3D illustration of an infinite mirror reflection cracking, representing the RecursionError maximum depth exceeded.

This error means a function is calling itself over and over again, in an infinite loop, until it hits a safety limit set by Python (usually 1,000 calls deep). This is when you encounter a RecursionError.

This is called Infinite Recursion.

The Cause

A “recursive function” is a function that calls itself. This is a powerful technique, but it must have a “base case”—a condition that tells it when to stop.

Problem Code (Missing Base Case): Let’s write a function to count down to 0.

def count_down(n):
    print(n)
    count_down(n - 1) # Function calls itself

count_down(5)
# Output:
# 5
# 4
# 3
# ...
# 0
# -1
# -2
# ... (CRASH!) RecursionError

It never knew when to stop!

The Fix: Add a “Base Case”

We need to add an if statement that says, “When you reach 0, just return and stop calling yourself.”

def count_down(n):
    # BASE CASE:
    if n < 0:
        return
    
    print(n)
    count_down(n - 1)
count_down(5)
# Output:
# 5
# 4
# 3
# 2
# 1
# 0
# (No crash)

If you get this error, look at your function and ask: “What is my stop condition?”

Similar Posts

Leave a Reply