2014-02-27 61 views
0

我的代码如下:名称错误if/else语句评价

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

当我运行它,它返回输入= 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,并且设置了python3以允许pygame更有效地工作。我添加了:

from __future__ import division, absolute_import, print_function, unicode_literals 

使python能够使用python3功能。

+0

我知道这不是你的主要问题 - 但我不认为你想'猜测==输入(“这是什么动物?”) - 使用'=='是一个逻辑比较,而不是任务。 –

回答

1

在Python 2中,您应该使用raw_input()而不是input()来获取未评估的输入。也就是说,input()将在返回给您之前评估用户输入。

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

btw,前两行似乎有一些缩进问题?

else: 
print("that is incorrect!") 

编辑:

如果有一天你想切换到Python 3,千万记住这里提到的raw_input()在Python 3被重命名为input()你将不得不使用eval(input())来得到旧的input()行为(这在我看来有点危险...)

0

有两个问题,一个是另一个,我相信是:guess == input(“这是什么动物?”) 。按照变化波纹管!

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