我用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")
这是我得到的错误:
追踪(最近一次通话):文件"C:\Python27/programs/2",第4行,位于如果(答案)==是:NameError:未定义名称"yes"
您没有名为yes
的变量,
您要做的是将用户输入与字符串"yes"
进行比较
哪个会像:
if answer == "yes":
# do stuff
答案周围也不需要括号。
answer
是一个字符串,您应该使用answer == "yes"
您需要在字符串中放入"
或'
。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"
。