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

Question:

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 ?

Asked By: Mr.spook

||

Answers:

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.

Answered By: AKX
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.