-2

if the user inputs a string at "how many would you like? (1-10)>" i want the try statement to re run instead of getting a NameError to get a proper integer input.

I must use try/except statements for my college assignment

This question is different because I cannot format it to the link specified by an admin, i have to adhere to my professors required syntax.

cont = str("y") 
item_cnt = 0          # running count of number of items ordered
order_total = 0.0     # accumulate total dollars
price = 3.5           # all cookies rae $3.50 per box

# banner
print("Thank you for placing your order")
cust = input("please enter your name> ")

# validate data entry

while cont.lower() == "y":

    valid_data = False 

    # input and data validation

    while not valid_data: 
        # display cookie list
        print("please choose a flavor:")
        print("num\tflavor")
        print("1.\tSavannah")
        print("2.\tThin Mints")
        print("3.\tTagalongs")
        print()

        item = input("enter item number> ")

        if item == "1" or item == "2" or item == "3":
            valid_data = True
        else:
            print("That was not a valid choice, please try again")

    valid_data = False # reset boolean flag

    while not valid_data:


        try:
            qty = int(input("How many would you like? (1-10)> "))
        except Exception as detail:
            print("Error: ", detail)
        else:
            if qty >= 1 and qty <= 10:
                valid_data = True



        # determine totals
        item_total = qty * price

        # determine cookie name for output display
        if item == 1:
            name = "Savannah"
        elif item == 2:
            name = "Thin Mints"
        else:
            name = "Tagalongs"


    # verify inclusion of this item
    valid_data = False

    while not valid_data:

        incl = input("would you like to add this to your order (y/n)> ")
        print()

        if incl.lower() == "y":
            order_total = order_total + item_total
            item_cnt = item_cnt + 1
            valid_data = True
            print ("{} was added to your order".format(name))
        elif incl.lower() == "n":
            print("{} was not added to your order".format(name))
            valid_data = True
        else:
            print("that was not a valid response, please try again")



    cont = input("\nwould you like to add another? (y/n)> ")




print("order for {}".format(cust))
print("Total Items = {}".format(item_cnt))
print("Total Boxes = {}".format(qty))
print("Total Cost = ${}".format(item_total))
print()
print("Thank you for your order")       

i want the "how many would you like? (1-10)>" try statement to re run until the code receives a proper integer.

I seemed to have fixed the problem by adding a continue after a ValueError

while not valid_data:
        try:
            qty = int(input("How many would you like? (1-10)> "))
        except ValueError as detail:
            print("Error: ", detail)
            continue
        except Exception as detail:
            print("Error: ", detail)
        else:
            if qty >= 1 and qty <= 10:
                valid_data = True
John
  • 9
  • 3
  • 1
    One possible way: make your code into function that takes the input, checks the input, and then call the function again if it fails the condition. – Paritosh Singh Feb 16 '19 at 22:30

1 Answers1

0

Just move this code:

# determine totals
item_total = qty * price

# determine cookie name for output display
if item == 1:
    name = "Savannah"
elif item == 2:
    name = "Thin Mints"
else:
    name = "Tagalongs"

outside of the innermost while block. It seems like the only reason your code isn't working is this line being in the 'while' loop:

item_total = qty * price

as 'qty' won't be defined if you threw an exception. You're getting an exception here if the user enters a non-number, right? There's no reason to have the stuff below that in the loop either, as that doesn't do you any good if you're going to loop around because of bad input.

One interesting thing...if you enter a number <1 or >10 first, and THEN enter letters or whatever, your code will work, as 'qty' will then have a value.

  • I just noticed that you say you don't want the "NameError". So then just don't print it. To do that, just replace the print statement in the catch block with 'pass'. –  Feb 16 '19 at 22:55