Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Set recurions limit

import sys

print(sys.getrecursionlimit())
sys.setrecursionlimit(10)

def recursion(n):
    print(f"In recursion {n}")
    recursion(n+1)

recursion(1)

Output:

1000
In recursion 1
In recursion 2
In recursion 3
In recursion 4
In recursion 5
In recursion 6
In recursion 7
Traceback (most recent call last):
  File "/home/gabor/work/slides/python/examples/functions/recursion_set_limit.py", line 10, in <module>
    recursion(1)
  File "/home/gabor/work/slides/python/examples/functions/recursion_set_limit.py", line 8, in recursion
    recursion(n+1)
  File "/home/gabor/work/slides/python/examples/functions/recursion_set_limit.py", line 8, in recursion
    recursion(n+1)
  File "/home/gabor/work/slides/python/examples/functions/recursion_set_limit.py", line 8, in recursion
    recursion(n+1)
  [Previous line repeated 4 more times]
  File "/home/gabor/work/slides/python/examples/functions/recursion_set_limit.py", line 7, in recursion
    print(f"In recursion {n}")
RecursionError: maximum recursion depth exceeded while calling a Python object