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

时间:2014-02-27 04:33:25

标签: python input namespaces choice

我的代码如下:

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功能。

2 个答案:

答案 0 :(得分:1)

在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()在python 3中被重命名为input()。你必须使用eval(input())来得到旧的input()行为(在我看来这有点危险......)

答案 1 :(得分:0)

有两个问题,一个是别的,另一个我认为是:猜= =输入(“这是什么动物?”)。按照下面的改变!

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? ")