You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计Python递归程序中'hello world'的打印次数?

统计递归过程中'hello world'的打印次数

原递归代码及运行结果如下:

原代码

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

要统计hello world的打印次数,可通过以下几种实用方法实现:


方法1:使用全局变量计数

定义全局变量作为计数器,每次打印hello world时递增计数,最后在捕获异常后输出结果:

count = 0

try:
    def iwillcall():
        global count
        def repeat_me():
            global count
            count += 1
            print('hello world')
            print(iwillcall())
        print(repeat_me())   
    iwillcall()
except RecursionError:
    print(f'you reached the limit, "hello world" printed {count} times')

方法2:使用非局部变量(nonlocal)避免全局变量

将计数器放在外层作用域,用nonlocal关键字让内层函数可修改该变量,更符合封装原则:

try:
    count = 0
    def iwillcall():
        nonlocal count
        def repeat_me():
            nonlocal count
            count += 1
            print('hello world')
            print(iwillcall())
        print(repeat_me())   
    iwillcall()
except RecursionError:
    print(f'you reached the limit, "hello world" printed {count} times')

方法3:让递归函数返回计数(无额外变量)

修改递归逻辑,让每个函数调用返回当前层计数加下层递归计数,无需额外变量:

try:
    def iwillcall():
        def repeat_me():
            print('hello world')
            # 当前层贡献1次,累加下层递归的计数
            return 1 + iwillcall()
        return repeat_me()   
    total = iwillcall()
except RecursionError:
    print(f'you reached the limit, "hello world" printed {total} times')

注:此方法需移除原代码中print(repeat_me())和print(iwillcall())的打印逻辑,避免干扰函数返回值。

内容的提问来源于stack exchange,提问作者user19944660

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:55:16