-1

I am trying to make sure that the user enters only "s/r/e" in the shipping method input. 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. 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)
moo moo
  • 9
  • 2
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Pranav Hosangadi Jul 08 '22 at 16:54

1 Answers1

1

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"

P.S. the try/except while defining shipping_method is unnecessary - input always returns a string and raises no errors

The Thonnu
  • 3,578
  • 2
  • 8
  • 30