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

Unbound recursion

  • In order to protect us from unlimited recursion, Python limits the depth of recursion:


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

recursion(1)

Output:

...
In recursion 995
In recursion 996
Traceback (most recent call last):
  File "recursion.py", line 7, in <module>
    recursion(1)
  File "recursion.py", line 5, in recursion
    recursion(n+1)
  File "recursion.py", line 5, in recursion
    recursion(n+1)
  File "recursion.py", line 5, in recursion
    recursion(n+1)
  [Previous line repeated 992 more times]
  File "recursion.py", line 4, in recursion
    print(f"In recursion {n}")
RecursionError: maximum recursion depth exceeded while calling a Python object