Python如何处理无限递归? [英] How does Python handle infinite recursion?

查看:92
本文介绍了Python如何处理无限递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在使用Python玩耍时,我注意到程序的堆栈大小基本上没有限制(对数字执行幂运算,即使达到了几千位数,精度仍然保持完美).这让我感到奇怪:如果我不小心陷入了Python中的无限递归循环,该怎么办?编译器会通知并抛出堆栈溢出错误吗?还是程序会崩溃?我的CPU会燃烧吗?老实说,这不是我渴望测试的事情.

So when toying with Python, I noticed that there is basically no limit on the program's stack size (kept performing power operations on a number, the precision stayed perfect even after getting to like thousands of digits). This makes me wonder: what if I accidentally got into an infinite recursive loop in Python? Would the compiler notice and throw a stack overflow error? Or would the program just crash? Would my CPU combust? This isn't something that I'd be eager to test myself, honestly.

推荐答案

现代计算机不会由于用户代码而燃烧.自己尝试一下:

No modern computer is going to combust due to user code, I promise. Try it for yourself:

def recurseInfinitely( n ):
    recurseInfinitely(n+1)

recurseInfinitely(0)

运行该程序会立即产生输出:

Running this program promptly yields the output:

  [...]
    recurseInfinitely(n+1)
  File "so.py", line 2, in recurseInfinitely
    recurseInfinitely(n+1)
  File "so.py", line 2, in recurseInfinitely
    recurseInfinitely(n+1)
RuntimeError: maximum recursion depth exceeded   

您可以捕获错误并检查 n 的值:

You can catch the error and check the value of n:

def recurseInfinitely( n ):   
    try:
        recurseInfinitely(n+1)
    except RuntimeError:
        print "We got to level %s before hitting the recursion limit."%n

并获得:

在达到递归限制之前,我们已达到997级.

We got to level 997 before hitting the recursion limit.

这篇关于Python如何处理无限递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆