pythonlistwhile-loop

using while loop to check errors with inputs in a list


I've been making a program on Python...

selected_pizzas=[] #creates an empty list 
for n in range(pizza_number): 
    selected_pizzas = selected_pizzas + [int(input("Choose a pizza: "))]

that will let the user input up to 5 numbers and store them in an empty list (selected_pizzas) the the user is only allowed to enter numbers from 0-11, I had a method of using while loops to check errors with the users inputs but I tried and it didn't seem to work with the numbers being inputted in the list:

pizza_number=0
goodpizza_number=False 
while not goodpizza_number:
    try:
        pizza_number= int(input("How many Pizzas do you want? (MAX 5): "))
        if pizza_number ==0 or pizza_number > 5: #if the number of pizzas asked for is 0 or over 5 it will give an error message and repeat question
            print("Not a correct choice, Try again")
        else:
            goodpizza_number=True 
    except ValueError:
        print("Not a number, Try again")

How would I use this method (above) to make sure the user is inputting the expected inputs(numbers from 0-11) in the first piece of code shown in the question? Thanks


Solution

  • You could do:

    selected_pizzas=[] #creates an empty list 
    while len(selected_pizzas) < pizza_number:
        try:
            pizza_selection = int(input("Choose a pizza: "))
        except ValueError:
            print("Not a number, Try again")
        else:
            if 1 <= pizza_selection <= 11:
                selected_pizzas.append(pizza_selection)
    

    This will make sure you still get the correct number of pizzas even after user errors.