Search code examples
pythonerror-handlingindex-error

How to check if a users input is valid against a list/tuple of pizzas?


Sorry if this question has been asked before, but I couldn't find the exact answer or a close-enough in other questions. I am also fairly new to Python.

I am looking for a way to check if a users input is valid when selecting pizzas out of the tuple. (e.g if the user inputs anything over 11 in my case I would want the program to restart the function.)

Here is the full code of my program so far.

def amountFunction():
    global pizzaAmount
    pizzaAmount = []
    while pizzaAmount is not int:
        try:
            pizzaAmount = int(input("Please input the amount of pizzas you would like - (a maximum of 5)"))
        except ValueError:
            print("Please input a value above 0 or less than 5")
        except pizzaAmount ==0 or pizzaAmount > 5:
            print("Please input a value above 0 or less than 5")
            amountFunction()
        else:
            print("Your amount of pizzas is " + str(pizzaAmount))
            break


amountFunction()

def selectFunction():
    global pizzas_with_prices
    pizzas_with_prices = [("BBQ Meatlovers", 8.5), ("Chicken Supreme", 8.5), ("Peri-Peri Chicken", 8.5),
                      ("Vegorama", 8.5), ("Cheesy Bacon Hawaiian", 8.5), ("Beef and Onion", 8.5),
                      ("Simply Cheese", 8.5), ("Ham and Cheese", 13.5), ("Hawaiian", 13.5),
                      ("Veg Trio", 13.5), ("Peperoni", 13.5), ("Wedge", 13.5)]
    for index, pizza in enumerate(pizzas_with_prices):
    print("%d %s: $%s" % (index, pizza[0], pizza[1]))
    global selected_pizza
    selected_pizza=[]
    for n in range(pizzaAmount):
        while selected_pizza is not int:
            try:
                selected_pizza = selected_pizza + [int(input("Choose a pizza: "))]
            except ValueError:
                print("Please select a pizza on the list")
            else:
                break
    global total_price
    total_price = 0
    for selected in selected_pizza:
        total_price += pizzas_with_prices[selected][1]


selectFunction()

def totalFunction():
    print("Here are your selected pizzas")
    for selected in selected_pizza:
        print("%s: $%s" % pizzas_with_prices[selected])

    print("Here is the total price of pizzas:${}".format(total_price))

totalFunction()

The function in question is this one below - def selectFunction():

def selectFunction():
    global pizzas_with_prices
    pizzas_with_prices = [("BBQ Meatlovers", 8.5), ("Chicken Supreme", 8.5), ("Peri-Peri Chicken", 8.5),
                      ("Vegorama", 8.5), ("Cheesy Bacon Hawaiian", 8.5), ("Beef and Onion", 8.5),
                      ("Simply Cheese", 8.5), ("Ham and Cheese", 13.5), ("Hawaiian", 13.5),
                      ("Veg Trio", 13.5), ("Peperoni", 13.5), ("Wedge", 13.5)]
    for index, pizza in enumerate(pizzas_with_prices):
       print("%d %s: $%s" % (index, pizza[0], pizza[1]))
    global selected_pizza
    selected_pizza=[]
    for n in range(pizzaAmount):
        while selected_pizza is not int:
            try:
                selected_pizza = selected_pizza + [int(input("Choose a pizza: "))]
            except ValueError:
                print("Please select a pizza on the list")
            else:
                break
    global total_price
    total_price = 0
    for selected in selected_pizza:
        total_price += pizzas_with_prices[selected][1]


selectFunction()

How would I go about checking if a users input is on the list/tuple of pizzas? (e.g if a user inputs 999 for selected_pizza I would want the program to repeat selectFunction() again until a valid pizza(s) is selected then move on to totaling the price of the pizzas and then moving on to the next function totalFunction() )

I have tried using IndexError: but it appears that I don't understand how to use it as it doesn't seem to work either skipping over and giving me an error or getting into an infinite loop. Essentially I need a way of handling an index error.

Below is an example of what happens at the moment.

Please input the amount of pizzas you would like - (a maximum of 5)2
Your amount of pizzas is 2
0 BBQ Meatlovers: $8.5
1 Chicken Supreme: $8.5
2 Peri-Peri Chicken: $8.5
3 Vegorama: $8.5
4 Cheesy Bacon Hawaiian: $8.5
5 Beef and Onion: $8.5
6 Simply Cheese: $8.5
7 Ham and Cheese: $13.5
8 Hawaiian: $13.5
9 Veg Trio: $13.5
10 Pepperoni: $13.5
11 Wedge: $13.5
Choose a pizza: 23456
Choose a pizza: 4235464
Traceback (most recent call last):
  File "C:\Users\ilyas rosslan\Documents\Python Work\tester.py", line 45, in 
<module>
   selectFunction()
  File "C:\Users\ilyas rosslan\Documents\Python Work\tester.py", line 42, in 
selectFunction
    total_price += pizzas_with_prices[selected][1]
IndexError: list index out of range

Would highly appreciate it if somebody could help. Thanks

Ilyas.


Solution

  • Read the input, validate it, then add it to the selected_pizza list.

    for n in range(pizzaAmount):
        while True:
            try:
                selection = int(input("Choose a pizza: "))
                if selection in range(len(pizza_with_prices)):
                    selected_pizza.append(selection)
                    break
                else:
                    print("Please select one of the listed pizza numbers")
            except ValueError:
                print("Please select a pizza on the list")
    

    while selected_pizza is not int: is not correct. That condition will always be true, since selected_pizza is a list, and a list is not int.

    You should also stop using so many global variables. amountFunction() should return the amount, and then it should be passed as an argument to selectFunction().