2

I am trying to understand recursion, so I have written a simple program to run a for loop using recursion:

#for loop code
n = 955 
for i in range(n+1):
    if(i==n):
        print(i)

outputs

955

Below code is a recursive version of the for loop code snippet:

def fun(i,n):
    if(i==n):
        print(i)
        return 
    fun(i+1,n)
fun(0,999) # calling function by passing index and N 

I am getting an error when I set n to be 999:


Traceback (most recent call last):
  File "/home/jdoodle.py", line 5, in <module>
    fun(0,999)
  File "/home/jdoodle.py", line 4, in fun
    fun(i+1,n)
  File "/home/jdoodle.py", line 4, in fun
    fun(i+1,n)
  File "/home/jdoodle.py", line 4, in fun
    fun(i+1,n)
  [Previous line repeated 995 more times]
  File "/home/jdoodle.py", line 2, in fun
    if(i==n):
RecursionError: maximum recursion depth exceeded in comparison

But when I run the following code by passing n as 955:

def fun(i,n):
    if(i==n):
        print(i)
        return 
    fun(i+1,n)
fun(0,955)

I am getting no error output as

955

Why there is an error when n=999 or above in recursive code in online compilers. How can I avoid these errors? The online compiler that I have used is: https://www.jdoodle.com/python3-programming-online/.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
Gopi Sai
  • 75
  • 1
  • 7
  • The default recursion limit in Python is 1000 levels. – Barmar Mar 02 '22 at 04:31
  • You have identified the issue quite precisely. Each recursive call takes memory for the stack frame, so there is an arbitrary limit on how deep you can do. Normal code doesn't recurse that deep, so it's almost always an error. – Tim Roberts Mar 02 '22 at 04:31

1 Answers1

4

Python, by default, has a recursion depth limit of 1000. Passing in 999 for n will exceed this limit, but passing in 955 will not.

You can verify the recursion limit by using:

import sys

print(sys.getrecursionlimit()) # Prints 1000
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33