2016-11-03 72 views
0
# asks the question and gives the choices 
choice=input('what is your favourite colour? press 1 for red, 2 for blue, 3 for yellow or 4 to quit') 
# if the responder responds with choice 1 or 2,3,4 it will print this 
if choice=='1' or 'one': 
    print('red means anger') 

elif choice=='2'or 'two': 
    print('blue represents calmness') 
elif choice=='3' or 'three': 
    print('yellow represents happiness') 
elif choice=='4' or 'four': 
    print('it was nice meeting you. goodbye.') 
else: 
    print('sorry incorrect answer please try again.') 

我的一個學生寫了這個,我似乎無法得到它的工作。 幫助!它不斷重複紅色意味着憤怒。如果我註釋掉'或', 它有效,但爲什麼她不能使用'或'?我希望她添加一個循環,但只有 ,如果這項工作第一。IF語句被忽視或不接受的邏輯運算符「或」

+0

你或語句被解讀爲此爲(選擇== 1)或'one'),評估'one'永遠是對的 – Skycc

+0

這是哪一種語言? Visual Basic.net? – Dronz

回答

0

下面,支架使事情更清晰

if (choice=='1') or (choice=='one'): 

或者,當你有多個OR語句被覈對的值,可以考慮把所有的校驗值的列表,並使用類似下面,這看起來更乾淨,我當值,以檢查增加

if choice in ['1', 'one', '2', 'two', '3', 'three']: 
+0

@David Schwartz,感謝您指出了這一點,儘管DivingTraube已經給出了答案,但對原始問題做了一些解釋,建議將後者作爲替代方案 – Skycc

3

or未正確使用。你需要寫

choice == '1' or choice == 'one' 

否則強制類型轉換將評估「一」至真和第一的or條件if語句總是true(一同義反復)和其他情況下從不檢查。當你有一個像

if choice=='1' or 'one': 

它會被當作

if (choice=='1') or 'one': 

「一」語句將始終評估爲True,因此如果條件總是滿足,你需要的是爲

+0

謝謝。 Python早期開始,我正在理解如何調試! –