如何检查用户输入是否对比萨饼/列表有效?

时间:2018-04-26 09:39:07

标签: python error-handling index-error

很抱歉,如果之前已经问过这个问题,但我找不到确切的答案,或者在其他问题上找不到。我也是Python的新手。

我正在寻找一种方法来检查用户输入在从元组中选择披萨时是否有效。 (例如,如果用户在我的情况下输入超过11的任何内容,我希望程序重新启动该功能。)

到目前为止,这是我的程序的完整代码。

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()

有问题的函数如下所示 - 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()

我如何检查用户输入是否在比萨饼的列表/元组中? (例如,如果用户为selected_pizza输入999,我希望程序再次重复selectFunction(),直到选择了有效的披萨,然后继续总计比萨饼的价格,然后转到下一个函数totalFunction() )

我尝试过使用IndexError:但似乎我不明白如何使用它,因为它似乎无法跳过并给我一个错误或进入一个无限循环。基本上我需要一种处理索引错误的方法。

下面是目前发生的事情的一个例子。

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

如果有人可以提供帮助,我们将非常感激。感谢

伊利亚斯。

2 个答案:

答案 0 :(得分:0)

阅读输入,验证输入,然后将其添加到selected_pizza列表。

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:不正确。该条件始终为真,因为selected_pizza是一个列表,而列表不是int

您还应该停止使用这么多全局变量。 amountFunction()应返回金额,然后将其作为参数传递给selectFunction()

答案 1 :(得分:0)

根据我的理解,我会这样做。我创建了一个单独的功能,用于选择一个有效的比萨饼,然后添加到功能中以选择多个比萨饼。

def amountFunction():
    try:
        pizzaAmount = int(input("Please input the amount of pizzas you would like - (a maximum of 5)"))
        if pizzaAmount > 0 and pizzaAmount <=5:
            return pizzaAmount
        else:
            print("Please input a value above 0 or less than 5")
            return amountFunction()
    except ValueError:
        return amountFunction()
    except KeyboardInterrupt:
        print("user aborted the program")
        return 0


def selectOnePizza(pizzas_with_prices):
    try:
        selected_pizza = int(input("Choose a pizza: "))
        if selected_pizza >= 0 and selected_pizza <len(pizzas_with_prices):
            return selected_pizza
        else:
            print("Please input a value above {} or less than {}".format(0,len(pizzas_with_prices)))
            return selectOnePizza(pizzas_with_prices)
    except ValueError:
        print("Please input a value above {} or less than {}".format(0,len(selected_pizza)))
        return selectOnePizza(pizzas_with_prices)
    except KeyboardInterrupt:
        print("user aborted the program")
        return -1


def selectManyPizzas(pizzas_with_prices, pizzaAmount):

    for index, pizza in enumerate(pizzas_with_prices):
       print("%d %s: $%s" % (index, pizza[0], pizza[1]))
    selected_pizza=[]

    for n in range(pizzaAmount):
        selected_pizza.append(selectOnePizza(pizzas_with_prices))
    return selected_pizza

def showSlectedPizzas(pizzas_with_prices, selected_pizza):
    print("Here are your selected pizzas")
    total_price = 0
    for selected in selected_pizza:
        print("%s: $%s" % pizzas_with_prices[selected])
        total_price = total_price + pizzas_with_prices[selected][1]

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


pizzaAmount = amountFunction()
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)]
selected_pizza = selectManyPizzas(pizzas_with_prices,pizzaAmount)

showSlectedPizzas(pizzas_with_prices, selected_pizza)

我希望它有所帮助。