简体   繁体   中英

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 aloud 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM