← Back

Home â€ē Errors â€ē RecursionError

RecursionError: your function never stops calling itself

Exception: RecursionErrorCategory: runtimeRaised at: when the call stack passes the recursion limit (1000 by default)

What this error means

Every function call pushes a frame onto the call stack, holding its arguments and local variables. That stack is finite — CPython allows 1000 nested calls by default — and when a function keeps calling itself without ever returning, the stack fills up and Python stops the program with RecursionError instead of letting it crash the interpreter with a real stack overflow.

So the limit is a safety net, not the bug. The bug is that your recursion has no exit, or its exit is unreachable. Raising the limit only delays the crash and buys a larger memory bill.

Cause 1 — no base case at all

def countdown(n):
    print(n)
    return countdown(n - 1)   # nothing ever stops it

countdown(5)
5
4
3
2
1
0
-1
-2
...
Traceback (most recent call last):
  File "demo.py", line 5, in <module>
    countdown(5)
  File "demo.py", line 3, in countdown
    return countdown(n - 1)
           ^^^^^^^^^^^^^^^
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

The repeated-line notice is the giveaway: [Previous line repeated 996 more times] means the same call site recursed a thousand times. Add the base case — the condition under which the function returns without recursing:

def countdown(n):
    if n <= 0:          # base case first
        return 0
    print(n)
    return countdown(n - 1)

Cause 2 — a base case that is never reached

The base case exists but the recursive step does not move towards it. Counting up towards a zero check, or stepping by a fraction, never lands:

def count_up(n):
    if n == 0:            # n starts at 1 and only grows
        return 0
    return 1 + count_up(n + 1)

def halve(n):
    if n == 1:            # 7 -> 3.5 -> 1.75 -> ... never equals 1
        return n
    return halve(n / 2)

Two habits prevent this. Test the base case with <= or >= rather than == so overshooting still terminates, and make sure the argument strictly shrinks on every call — n - 1, n // 2, items[1:].

Cause 3 — mutual recursion and accidental self-calls

Two functions can recurse into each other (is_even calls is_odd which calls is_even), which looks like neither is recursive when you read one of them. And a very common typo: calling the function where you meant to call a helper or a method, so the outer function calls itself:

def total(items):
    if not items:
        return 0
    return items[0] + total(items)   # meant total(items[1:]) — items never shrinks

When the recursion is legitimately deep

Sometimes the data really is 100,000 levels deep — a linked list, a nested tree, a parser. Then rewrite the recursion as a loop with an explicit stack; it is faster, uses far less memory and cannot overflow:

def sum_list(items):
    total = 0
    for n in items:      # no frames, no limit
        total += n
    return total

sys.setrecursionlimit(10000) raises the guard, but each frame still costs real memory and the C stack underneath is not actually unlimited — push it far enough and the process segfaults instead of raising a clean error. Raise it modestly, and prefer the loop. For repeated recursion over the same inputs, add functools.lru_cache so overlapping subproblems stop re-recursing.

How to debug it

  1. Read the traceback: one line repeated hundreds of times names the exact call site that recurses.
  2. Print the argument on entry (print('n =', n)). If the value does not shrink towards the base case, you have found it.
  3. Check the base case is tested before the recursive call, not after — code after a recursive call never runs when the recursion is infinite.
  4. Check the comparison: == on a float or on a value that skips past zero never fires; use <=.
  5. If the input is genuinely huge, convert to a loop with an explicit stack instead of raising the limit.

Related pages

đŸ‡ŽđŸ‡ŗ Hindi ā¤ŽāĨ‡ā¤‚ ā¤¸ā¤Žā¤āĨ‡ā¤‚

RecursionError: maximum recursion depth exceeded ka matlab hai function khud ko baar-baar call karta raha aur kabhi return nahi hua. Python ki call stack ki default limit 1000 hai; uske baad wo program rok deta hai. Sabse common wajah: base case missing hai, ya base case aisa hai jo kabhi satisfy hi nahi hota (jaise if n == 0 jab n badhta ja raha hai, ya float 1.0 tak kabhi pahunchta hi nahi). Fix: base case ko sabse pehle check karo, == ki jagah <= lagao, aur har recursive call me argument ko chhota karo (n - 1, items[1:]). Limit badhana (sys.setrecursionlimit) asli fix nahi hai — memory to lagegi hi, aur bahut zyada badhane par process crash ho jata hai. Bada data ho to loop use karo.

Python functions Hindi ā¤ŽāĨ‡ā¤‚ ā¤Ēā¤ĸā¤ŧāĨ‡ā¤‚ →