gpt4 book ai didi

python - if/else 语句评估的名称错误

转载 作者:行者123 更新时间:2023-12-04 17:03:54 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





error in python d not defined. [duplicate]

(3 个回答)


7年前关闭。




我的代码如下:

else:
print("that is incorrect!")
choice = input("Would you like to (g)uess again, or (q)uit? ")
if choice == "g":
guess == input("What animal is this? ")
elif choice == "q":
game_running = False
else:
print("That is not a valid option")
choice = input("Would you like to (g)uess again, or (q)uit? ")

当我运行它时,它为 input = g、q 或其他任何东西返回以下内容。
Traceback (most recent call last):
File "Project1.py", line 102, in <module>
choice = input("Would you like to (g)uess again, or (q)uit? ")
File "<string>", line 1, in <module>
NameError: name 'g' is not defined

我以前曾多次使用这种评估用户猜测的格式,但从未遇到任何问题。任何建议将不胜感激!我在 Mac OSX 上运行 pygame,我将 python 设置为关闭 python3 以允许 pygame 更有效地工作。我已经添加了:
from __future__ import division, absolute_import, print_function, unicode_literals

使python能够使用python3功能。

最佳答案

在 python 2 中,你应该使用 raw_input()而不是 input()获得未评估的输入。即input()将在返回给您之前评估用户输入。

choice = raw_input("Would you like to (g)uess again, or (q)uit? ")

顺便说一句,前两行似乎有一些缩进问题?
else:
print("that is incorrect!")

编辑:

如果有一天你想切换到 python 3,请记住 raw_input()正如这里提到的被重命名为 input()在 python 3. 你必须使用 eval(input())拿旧 input()行为(在我看来这有点危险......)

关于python - if/else 语句评估的名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22059106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com