python - 运行时错误 : Maximum Recursion Depth Exceeded when Using exit(0) in python

标签 python python-2.7

我正在学习 Zed Shaw 的“艰难地学习 Python”。

我目前正在学习第 36 课:http://learnpythonthehardway.org/book/ex36.html

我的问题:

我正在尝试根据 Zed 在第 35 课中所做的来创建我自己的游戏:http://learnpythonthehardway.org/book/ex35.html

在他的游戏中,他创建了以下函数来终止游戏:

def dead(why):
    print why, "Good job!"
    exit(0)

它用在 if/else 语句中,例如:

choice = raw_input("> ")

    if choice == "left":
        bear_room()
    elif choice == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you starve.")

当我运行他的程序时,它会在调用 dead 函数时退出。

但是,当我尝试在自己的代码中使用相同的构造时,出现以下错误:

RunTime Error: Maximum Recursion Depth Exceeded

在我的程序中调用 exit(0) 函数的代码行之后。

这是我如何在我的程序中使用它的示例:

def exit(message):
    print message, "Your adventure is over."
    exit(0)

像这样的 if/else 语句:

answer = raw_input("> ")

if "stay" in answer:
    exit("Adventure and excitement are only available to those who participate.")
elif "don't" in answer:
    exit("Great things were never achieved by cowards.  Please rethink your choice.")
elif "wait" in answer:
    exit("Great things were never achieved by cowards.  Please rethink your choice.")
elif "outside" in answer:
    exit("Adventure and excitement are only available to those who participate.")
elif "enter" in answer:
    lobby()
elif "go" in answer:
    lobby()
elif "through" in answer:
    lobby()
elif "inside" in answer:
    lobby()
else: 
    exit("Well, you're no fun!")

我不清楚为什么它在 Zed 的程序中有效,但在我自己的程序中却无效。 (是的,我知道这可能是对 elif 的过分使用,但我的编程能力不允许我现在做很多其他事情)。

起初我以为这是因为我在我的程序中使用 while 循环的方式,但我已经删除了所有这些并且我遇到了同样的问题。

谢谢。

最佳答案

这很简单。您将函数命名为 exit(),并且您的函数尝试调用名为 exit() 的函数。因此,您的函数会调用自身,然后一次又一次地调用自身...

当函数调用自身时,这称为递归 调用。如果你的函数一遍又一遍地调用自己太多次,最终会达到一个限制,Python 会停止你的程序。 Python 引发异常,告诉您已达到“最大递归深度”。

这是一个简单的修复:

import sys

def dead(why):
    print why, "Good job!"
    sys.exit(0)

现在您的程序明确要求一个特定的 exit() 函数,该函数位于 sys 中。它不会永远递归地调用自身,而是调用 sys.exit() 一次,您的程序就会停止。

另一种解决方案是将您的函数重命名为 exit() 以外的名称。 Zed 称他的 dead() 这就是他的示例有效的原因。

关于python - 运行时错误 : Maximum Recursion Depth Exceeded when Using exit(0) in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858618/

相关文章:

javascript - Raspberry Pi 上的 Web 界面

Python - 根据数组值将数组拆分为多个数组

python - 将标签列添加到数据框

javascript - 在 Linux 上部署 Javascript 应用程序的最简单方法

python - 使用 matplotlib 更改线条样式比例间距

python-2.7 - 从 Pandas 的另一列中填充一列的缺失值

python - 是否可以在 python 中迭代字典以在 html 电子邮件中使用

python - 属性错误 : install_layout when attempting to install a package in a virtual environment

python-2.7 - 如何使用pycharm编辑器加载预训练的graph.pb和重新训练的label.text

python - 手指宽度(计算机视觉)