1

I am having an issue with my index errors. This code below basically asks the customer to enter the corresponding number to their pizza choice (a list of pizzas with their index number is printed before this.) I want to make it so if the customer enters a number higher than 12 which is the highest pizza number on the list, it will ask you to Enter the corresponding number again, if that makes sense. I heard you could use try except errors but I don't really know how.

   pizzaItem = int(input("Please enter the corresponding number to your pizza choice: "))
    print("You have added", pizzaMenu[pizzaItem]  , "to your order")
    pizzaOrder.append(pizzaMenu[pizzaItem])
    while len(pizzaOrder) != customerPizzaNumber:
            pizzaItem = int(input("Please enter the corresponding number to your pizza choice: "))
            print("You have added", pizzaMenu[pizzaItem] , "to your order")
            pizzaOrder.append(pizzaMenu[pizzaItem])
    print(" ")
    print("Thanks for chosing your pizzas. Here is your current order:")

2 Answers2

0

You can do something like the following. This has a variable called pizza_choice. This will get set to None at the beginning of the script and it will only get set to a number when we can successfully turn it into an integer. So our while loop will keep asking the user for correct input until we can successfully determine that it is a number.

To have this work for your example, you may need to add some more checking to determine if the number they entered is allowed. Mine is just checking if it's a number. However, it looks like you may need to check if that number is in a specific range of choices.

pizza_choice = None

while pizza_choice is None:
    raw_response = input("Please enter your pizza number: ")

    if raw_response.isdigit():
        pizza_choice = int(raw_response)
    else:
        pass

print("Your selected pizza number is: {0}".format(pizza_choice))
Kyle
  • 1,056
  • 5
  • 15
0

Add this input check - it'll repeat the process until the user enters a number below 12:

pizzaItem = None
while pizzaItem is None:
    pizzaItem = input("Please enter the corresponding number to your pizza choice: "))
    if not (pizzaItem.isdigit() and 0 <= int(pizzaItem) <= len(pizzaMenu)):
        pizzaItem = None
    else:
        pizzaItem = int(pizzaItem)

print("You have added", pizzaMenu[pizzaItem]  , "to your order")
Todor Minakov
  • 19,097
  • 3
  • 55
  • 60
  • What does .isdigit() do? –  Sep 17 '17 at 06:16
  • 0 maybe a valid index for the pizza list, maybe use `None` as the sentinel and `int(pizzaItem) <= len(pizzaMenu)` in case more pizzas are added. – salparadise Sep 17 '17 at 06:17
  • Average_Coder isdigit() ["Return true if all characters in the string are digits and there is at least one character, false otherwise"](https://docs.python.org/3/library/stdtypes.html#str.isdigit); @salparadise thanks for the suggestion, it's good, edited the answer. – Todor Minakov Sep 17 '17 at 06:58