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