[英]Tip calculator issue
試圖為基於服務的小費計算器編寫python代碼,而我的while循環遇到問題。
service = ""
while service != "excellent" or service != "good" or service != "bad":
service = input("(Please choose excellent, good, or bad): ")
這部分導致無限循環,但我不確定為什么或如何解決...
您正在使用or
要在何處使用and
。
如果三個條件之一為真,則循環將繼續。
如果您的輸入是"excellent"
那么service != "good"
和service != "bad"
都是正確的,因此循環將繼續。 其他值也是如此。
您想要的是:
service = ""
while service != "excellent" and service != "good" and service != "bad":
service = input("(Please choose excellent, good, or bad): ")
更好的(以及各種評論者指出的更多Pythonic的)是:
service = ""
while service.lower() not in ["excellent", "good", "bad"]:
service = input("(Please choose excellent, good, or bad): ")
這更容易閱讀,並且在任何情況下(上,下,混合)都接受輸入。
在這種情況下,您要使用“和”而不是“或”。 但是,另一個更干凈的選擇是執行以下操作:
while service not in ['excellent', 'good', 'bad]:
service = input('(Please choose excellent, good, or bad): ')
這將測試service
的價值是否在可接受的答案列表中,並使以后的編輯更加容易。
現在,您要說的是“如果其中任何三個語句為真,則繼續while循環”。
您想要的是:
service = ""
while service != "excellent" and service != "good" and service != "bad":
service = input("(Please choose excellent, good, or bad): ")
您只是將邏輯混為一談-您正在使用or
代替and
。
無論您有什么輸入,都是(不好)或(不好)或(不錯)!
例如,即使您輸入“ good”,good仍為(不是優秀),因此總體條件返回True,並且您將繼續循環。
編寫此條件的更清晰方法是:
while service not in ["excellent", "good", "bad"]:
service = input("(Please choose excellent, good, or bad): ")
循環,直到任意數量的條件得到滿足(因為它是既不可能也沒有意義,以滿足所有的人都在一次),你需要循環,而所有的人都得不到滿足(邏輯否定)。 我能想到的最易讀和Python式的表達方式是:
service = ''
while service not in ('excellent', 'good', 'bad'):
service = input("(Please choose excellent, good, or bad): ")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.