我用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
答案 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"
进行比较。