try:
def iwillcall():
def repeat_me():
print('hello world')
print(iwillcall())
print(repeat_me())
iwillcall()
except RecursionError:
print('you reached the limit')
结果:
hello world
hello world
hello world
hello world
hello world
hello world
hello world
you reached the limit
我如何计算递归打印"你好世界"的次数?
以下解决方案使用全局变量
import sys
print(sys.getrecursionlimit()) # to get maximum recursion of the system you are using
i = 0
try:
def iwillcall():
global i
i = i+1
def repeat_me():
global i
i+=1
print('hello world')
print(iwillcall())
print(repeat_me())
iwillcall()
except RecursionError:
print('you reached the limit')
print(i+2)