2014-01-09 147 views
2

我剛剛開始使用python,並且陷入了一些在我看來應該工作的東西。這是我的第一個代碼,我只是試圖與用戶進行對話。Python - if語句工作不正確

year = input("What year are you in school? ") 
yearlikedislike = input("Do you like it at school? ") 
if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"): 
    print("What's so good about year " + year, "? ") 
    input("")  
    print("That's good!") 
    time.sleep(1) 
    endinput = input("I have to go now. See you later! ") 
    exit() 
if (yearlikedislike == "no" or "No" or "nope" or "Nope" or "NOPE"): 
    print("What's so bad about year " + year, "?") 
    input("") 
    time.sleep(1) 
    print("Well that's not very good at all") 
    time.sleep(1) 
    endinput = input("I have to go now. See you later! ") 
    time.sleep(1) 
    exit() 

我的問題是,即使我一個否定的答案回答它仍然可以與響應,如果我說是的答覆,如果我切換2左右(所以對於否定答案的代碼是上面的代碼爲正面答案),它總是會回覆,就好像我已經給出了否定的答覆。

回答

6
if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"): 

if yearlikedislike.lower() in ("yes","yep","yup"): 

會做的伎倆

+1

+1打我吧:) –

+2

您可能也想介紹'str。低' – iCodez

+0

同意。 YEP和YUP錯過了,更不用說其他組合了。 – mhlester

1

這是因爲條件被解釋爲:

if(yearlikedislike == "yes" or "Yes" == True or "YES" == True #... 

嘗試

if(yearlikedislike == "yes" or yearlikedislike == "Yes" or yearlikedislike == "YES"#... 

或更簡潔的方式:

if(yearlikedislike in ("yes", "Yes", "YES", #... 

更簡潔的方式:

if(yearlikedislike.lower() in ("yes", "yup", #... 

一個字符串(這裏「是」)轉換成布爾轉換爲true,如果它不是空

>>> bool("") 
False 
>>> bool("0") 
True 
>>> bool("No") 
True 

之後的每個部分或與之前無關。

還考慮使用else或elif而不是兩個相關的if。在測試它們之前儘量降低字符,這樣你就不需要測試了。

3

這是因爲Python正在評估"Yes"的「真實性」。

你的第一個if語句這樣解釋:

if the variable "yearlikedislike" equals "yes" or the string literal "Yes" is True (or "truthy"), do something

你需要比較針對每次yearlikedislike

試試這樣說:

if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"): 
    #do something 
2
if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"): 

字符串評估爲True。我知道你以爲你說如果像今年一樣喜歡這些東西,就繼續下去。但是,你實際上說的是:

if yearlikedislike equals "yes", or if "Yes" exists (which it does), or "YES" exists, etc: 

你想要的是兩種:

if (yearlikedislike == "yes" or yearlikedislike == "Yes" or yearlikedislike == "YES") 

或更好:

yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup")