2012-01-07 119 views
0

我寫了一個腳本與Python 2.7,這是代碼:爲什麼這個python代碼錯了?

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

你有沒有名爲yes
變量您要什麼做的是用戶輸入比較字符串"yes"

這會是這樣的:

if answer == "yes": 
    # do stuff 

也沒有必要圍繞答案的括號。

+0

謝謝堆!!! – user1135707 2012-01-07 08:09:07

1

answer是一個字符串,你要使用answer == "yes"

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"