2013-03-12 68 views
1

有一些小程序要求輸入爲char-y,b,s,然後通過比較它來檢查輸入是什麼。
的概率」,當我運行程序,如果輸入的是IS-字符串比較 - 未定義值

NameError: name 'b' is not defined

我得到,讓說,B。
這是我的代碼:

print("Please think of a number between 1 and 7") 
print("Is it 4? (y,s,b)") 
answer=char(input()) 

if (answer=='y'): 
    print("It is Four!") 

elif (answer=='s'): 
    print("Is it 2? (y,s,b)") 
    answer=input() 
    if (answer=='y'): 
     print("It is two!") 
    elif (answer=='s'): 
     print("It is one!") 
    elif (answer=='b'): 
     print("It is Three!") 
elif (answer=='b'): 
    print("Is it 6? (y,s,b)") 
    answer=input() 
    if (answer=='y'): 
     print("It is Six!") 
    elif (answer=='s'): 
     print("It is Five!") 
    elif (answer=='b'): 
     print("It is Seven!") 
+1

什麼是y b和s? – IcyFlame 2013-03-12 09:14:07

+0

是的,越來越小? – Ledhund 2013-03-12 09:15:51

+0

@ user2160077:使用'if'和'elif'時,請刪除括號。 – Matthias 2013-03-12 10:23:39

回答

3

既然你似乎是使用Python 2,你需要使用raw_input()而非input()。不同之處在於後者試圖評估你輸入的表達式。例如,如果輸入b,它會查找名爲b的變量。

在Python 3中,沒有raw_input()input()不再評估表達式。換句話說,Python3的input()的行爲就像Python2的raw_input()