Home > database >  Why i don't get the maximum recursion number in python?
Why i don't get the maximum recursion number in python?

Time:09-11

try:
    start = 0
    def recursion():
        global start
        def repeat():
            global start

            print('hello world')
            start  = 1
            print(recursion())
            
        print(repeat())

    print(recursion())
    
except RecursionError:
    print('you eached the limit')
    print(' ')
    print('recursion :',start, 'times')

result :

hello world
hello world
you eached the limit

recursion : 497 times

Why i don't get the maximum number of recursion in python or is this the maximum number ?

CodePudding user response:

The default recursion limit is 1000.

>>> sys.getrecursionlimit()
1000

A program with a single recursive function will reach 999:

start = 0

try:
    def recursion():
        global start
        start  = 1
        recursion()
    recursion()
except RecursionError:
    print('recursion :', start, 'times')

prints out

recursion : 999 times

Your program is creating a stack that has recursion(), then repeat(), then recursion(), etc., and a print() call, so it makes sense you reach a bit under half of that.

  • Related