简体   繁体   English

使用while循环检查列表中输入的错误

[英]using while loop to check errors with inputs in a list

i've been making a program on python... 我一直在用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: 这将允许用户输入最多5个数字并将它们存储在一个空列表(selected_pizzas)中,用户仅大声输入0-11之间的数字,我有一种使用while循环来检查用户输入错误的方法,但是我试过了,但似乎无法使用列表中输入的数字:

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 我将如何使用该方法(以上)来确保用户在问题中显示的第一段代码中输入了预期的输入(0-11之间的数字)

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. 这样可以确保即使出现用户错误,您仍然可以得到正确数量的披萨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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