为什么python告诉我,我的yes变量没有定义?

时间:2012-01-07 08:00:27

标签: python variables user-input

我用Python 2.7编写了这个脚本:

name=raw_input("Hi im a PC, who are you?")

print("Hi " + name + " how are you, are you good?")

answer = raw_input("")

if (answer) == yes:
    print("That's good to hear")
elif (answer) == no:
    print("Oh well")
else:
    print("Sorry, you didnt answer the question properly, Please answer with a yes or no")

这是我得到的错误:

Traceback (most recent call last):

File "C:/Python27/programs/2", line 4, in 

     if (answer) == yes:

NameError: name 'yes' is not defined

3 个答案:

答案 0 :(得分:3)

你没有名为yes的变量,
您要做的是将用户输入与字符串"yes"

进行比较

会是这样的:

if answer == "yes":
    # do stuff

回答中也没有必要使用这些括号。

答案 1 :(得分:1)

answer是一个字符串,您应使用answer == "yes"

答案 2 :(得分:0)

您需要在字符串中添加"'yes不是"yes"no不是"no"

#if (answer) == yes:
if (answer) == "yes":

#elif (answer) == no:
elif (answer) == "no":

错误name 'yes' is not defined是因为解释器查找了名为yes的变量,因为该单词没有"'。如果您写"yes",解释程序会将answer变量的值与字符串"yes"进行比较。