簡體   English   中英

Python 即使條件滿足也無法退出while循環

[英]Python I can't exit the while loop even though the condition is satisfied

我試圖編寫一個代碼來計算每個人在添加小費后應該支付的賬單金額,但我想將用戶限制在特定的小費百分比,如果他們選擇了其他東西,就會給他們一個錯誤。

所以,我想出了這個:

print("Welcome to the tip calculator.")

bill = float(input("What was the total bill?"))

people = int(input("How many people to split the bill?"))

perc = int(input("What percentage tip would you like to give? 10, 12, or 15?"))


total = float((bill + (bill * perc / 100)) / people)


while perc != 10 or perc != 12 or perc != 15:
    print("Error, please chose one of the given percentages.")
    perc = float(input("What percentage tip would you like to give? 10, 12, or 15?"))


else:
    print("Everyone should pay", total)

但是,即使我輸入 10、12 或 15,我也會收到“錯誤,請選擇給定百分比之一”。 信息。 我應該怎么辦?

你的情況應該是

if perc != 10 and perc != 12 and perc != 15:   

如果滿足所有這三個條件,您希望它得到滿足。 使用or ,如果其中任何一個條件滿足,則整個條件都滿足。

你可以用更短的方式寫:

if perc not in [10, 12, 15]:

你的邏輯很混亂。 如果 perc=10 那么它一定不是 perc=12 但如果滿足其中任何一個,你就會運行....嘗試將您的or更改為and or 更好的嘗試:

while perc not in [10, 12, 15]:
    print("Error, please chose one of the given percentages.")
    perc = float(input("What percentage tip would you like to give? 10, 12, or 15?"))

你的情況雖然搞砸了,而且你使用 else 這就是為什么你會出錯。 嘗試而不是使用循環。

print("Welcome to the tip calculator.")
bill = float(input("What was the total bill?"))
people = int(input("How many people to split the bill?"))
perc = int(input("What percentage tip would you like to give? 10, 12, or 15?"))
total = float((bill + (bill * perc / 100)) / people)
while perc not in [10, 12, 15]:
    print("Error, please chose one of the given percentages.")
    perc = float(input("What percentage tip would you like to give? 10, 12, or 15?"))
else:
    print("Everyone should pay", total)

利用:

while perc not in [10, 12, 15]:

更好(見上面的答案),

要了解您的問題,請嘗試以下操作:

while perc != 10 or perc != 12 or perc != 15:
    perc = float(input("What percentage tip would you like to give? 10, 12, or 15?"))
    print("10: ", perc != 10, "12: ", perc != 12, "15: ", perc != 15, "OR: ", perc != 10 or perc != 12 or perc != 15)`

結果是:

What percentage tip would you like to give? 10, 12, or 15?10
10.0
10:  False 12:  True 15:  True OR:  True
What percentage tip would you like to give? 10, 12, or 15?12
12.0
10:  True 12:  False 15:  True OR:  True
What percentage tip would you like to give? 10, 12, or 15?15
15.0
10:  True 12:  True 15:  False OR:  True

or邏輯和,每個數字中的兩個條件為真

真 + 真 + 假 = 真

真 + 假 + 真 = 真

假 + 真 + 真 = 真

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM