Search code examples
pythonrecursionruntime-errorpython-idlepython-3.3

Python, IDLE: Too many recursive errors


This is supposedly a problem with the IDLE editor for Python. (I'm running Python 3.3.0 on OSX, but the same problem occurs with 2.7.3)

I'm using IDLE to write Python programs. My problem is: Calling a recursive function, which calls itself too many times (1000 times), doesn't give me a single runtime error, but rather, it keeps sending me error messages until I close the program.

The error which it should be sending is: "RuntimeError: maximum recursion depth exceeded." The error which it sends a thousand times isntead is simply a point out to where in the script the problem is:

Traceback (most recent call last):
  File "<pyshell#112>", line 1, in <module>
    factorial(1.5)
  File "/Users/User/Documents/Python/Scripts/program1.py", line 187, in factorial
    recurse = factorial(n-1)
  File "/Users/User/Documents/Python/Scripts/program1.py", line 187, in factorial
    recurse = factorial(n-1)

etc.

This goes with all recursive functions calling itself too many times, but the specific function used here is:

def factorial(n):
    if n == 0:
        return 1
    else:
        recurse = factorial(n-1)
        result = n * recurse
        return result

Solution

  • To stop python from showing those hundreds of errors, you can use a try-except block:

    def factorial(n):
        if n == 0:
            return 1
        else:
            recurse = factorial(n-1)
            result = n * recurse
            return result
    try:
        print (factorial(6000))
    except RuntimeError as e:
        print (e)
    

    output:

    #print factorial(1000)
    93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
    
    #print factorial(6000)
    maximum recursion depth exceeded in comparison
    

    In your case this error occurs because python has a limit on the maximum recursion depth,it is there to stop the C stack from overflow. But you can change it using sys.setrecursionlimit:

    In [4]: import sys
    
    In [5]: sys.getrecursionlimit()
    Out[5]: 1000