[英]How can I handle 2 errors from user input in a while true loop
I am trying to make sure that the user enters only "s/r/e" in the shipping method input.我试图确保用户在运输方式输入中只输入“s/r/e”。 The program is not handling the errors correctly for shipping method input.程序未正确处理运输方式输入的错误。 I am able to handle the input errors for the number of items.我能够处理项目数量的输入错误。 I am wondering if I am able to handle multiple errors under a single while true block.我想知道我是否能够在一个 while true 块下处理多个错误。 Any other recommended solutions are greatly appreciated!非常感谢任何其他推荐的解决方案! This is what I have tried to do:这是我试图做的:
def mail_price_calculator(items, shipping_method):
if items <= 50:
cost = 3
if shipping_method == "s":
postage = 10
ship_by = "Standard post:"
elif shipping_method == "r":
postage = 15
ship_by = "Registered post:"
elif shipping_method == "e":
postage = 20
ship_by = "Express post:"
if items > 50:
cost = 2
if shipping_method == "s":
postage = 0
ship_by = "Standard post:"
elif shipping_method == "r":
postage = 10
ship_by = "Registered post:"
elif shipping_method == "e":
postage = 17
ship_by = "Express post:"
item_cost = items * cost
calculation = (items * cost) + postage
print("Receipt: ")
print(f"{items} items x ${cost} = ${item_cost}")
print(f"{ship_by} ${postage}")
print(f"Total: ${calculation}")
return calculation
while True:
try:
items = int(input("Enter the number of items: "))
except ValueError:
print("Sorry, please enter a number\n")
continue
if items == 0:
print("Sorry, number of item cannot be 0\n")
else:
break
while True:
try:
shipping_method = str(input("Enter shipping method (s/r/e): "))
except ValueError:
print("Please enter an alphabet: \n")
continue
if shipping_method != ("s", "r", "e", "S", "R", "E"):
print("Sorry, please enter a valid shipping method (s/r/e): \n")
else:
break
print()
mail_price_calculator(items, shipping_method)
Replace this line:替换这一行:
if shipping_method != ("s", "r", "e", "S", "R", "E")
with:和:
if shipping_method not in ("s", "r", "e", "S", "R", "E")
Or even:甚至:
if shipping_method.lower() not in "sre"
PS the try
/ except
while defining shipping_method
is unnecessary - input
always returns a string and raises no errors PS try
/ except
在定义shipping_method
时是不必要的 - input
总是返回一个字符串并且不会引发错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.