我试图编写一个代码来计算每个人在添加小费后应该支付的账单金额,但我想将用户限制在特定的小费百分比内,如果他们选择了其他东西,就会给他们一个错误。
所以,我想出了这个:
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,我也会得到"strong";错误,请从给定的百分比中选择一个"消息。我该怎么办?
您的条件应该是
if perc != 10 and perc != 12 and perc != 15:
如果这3个条件都得到满足,您希望它得到满足。使用or
,如果它们中的任何一个是,则整个条件都将得到满足。
你可以用更短的方式写:
if perc not in [10, 12, 15]:
您的逻辑一团糟。如果perc=10,那么它一定不是perc=12,但如果满足其中任何一个,则运行。。。。尝试将or
更改为and
或者最好试试:
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?"))
你的条件while被搞砸了,而且你还使用了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
或是逻辑和,在每个数字中,条件的两个是tru
真+真+假=真
真+假+真=真
假+真+真=真