2015-02-12 81 views
0

我試圖運行一個腳本,詢問用戶他們最喜歡的運動隊。這是我到目前爲止:用戶輸入的腳本

print("Who is your favorite sports team: Yankees, Knicks, or Jets?") 
if input is "Yankees": 
    print("Good choice, go Yankees") 
elif input is "Knicks": 
    print("Why...? They are terrible") 
elif input is "Jets": 
    print("They are terrible too...") 
else: 
    print("I have never heard of that team, try another team.") 

每當我運行這個腳本,最後的「else」函數接管用戶可以輸入任何內容之前。

另外,沒有一個團隊可供選擇。幫幫我?

+0

你有沒有定義的輸入? – tox123 2015-02-12 01:35:13

回答

3

輸入是詢問用戶答案的​​函數。

您需要調用它並將返回值賦給某個​​變量。

然後檢查該變量,而不是input本身。

注意 你可能想raw_input(),而不是得到你想要的字符串。

只記得去掉空白。

1

您的主要問題是您正在使用is來比較值。因爲它是在這裏的問題討論 - >String comparison in Python: is vs. ==

您使用==比較時價值和is比較時的身份。

你想改變你的代碼看起來像這樣:

print("Who is your favorite sports team: Yankees, Knicks, or Jets?") 
if input == "Yankees": 
    print("Good choice, go Yankees") 
elif input == "Knicks": 
    print("Why...? They are terrible") 
elif input == "Jets": 
    print("They are terrible too...") 
else: 
    print("I have never heard of that team, try another team.") 

但是,您可能要考慮把你的代碼放到一個while循環,使用戶提出的問題,直到你的答案與接受的答案。

您可能還想考慮添加一些人爲容錯功能,方法是將比較值強制爲小寫字母。這樣,只要團隊名稱拼寫正確,他們的比較就會準確無誤。

例如,請參見下面的代碼:

while True: #This means that the loop will continue until a "break" 
    answer = input("Who is your favorite sports team: Yankees, Knicks, or Jets? ").lower() 
#the .lower() is where the input is made lowercase 
    if answer == "yankees": 
     print("Good choice, go Yankees") 
     break 
    elif answer == "knicks": 
     print("Why...? They are terrible") 
     break 
    elif answer == "jets": 
     print("They are terrible too...") 
     break 
    else: 
     print("I have never heard of that team, try another team.") 
相關問題