簡體   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