繁体   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