繁体   English   中英

为什么python告诉我我的yes变量未定义?

[英]why does python tell me that my yes variable not defined?

我用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

您没有名为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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM