python - 如何检查用户输入对比萨列表/元组是否有效?

标签 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

如果有人可以帮助,将不胜感激。谢谢

伊利亚斯

最佳答案

读取输入,对其进行验证,然后将其添加到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:不正确。该条件将始终为true,因为selected_pizza是一个列表,而列表不是int

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

关于python - 如何检查用户输入对比萨列表/元组是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50039694/

相关文章:

Python索引错误: list index out of range when using a list as an iterable

python - IndexError尝试在python中数值求解差分方程

python - Python如何清空已使用的内存?

python - UnicodeDecodeError : 'charmap' codec can't decode byte 0x81 in position 49: character maps to <undefined>

python - 如何使用 python 列出应用于 azure 资源组的锁

c - c中unix_error函数的问题

python - 索引错误 : string index out of range while working with random module

python - 获取函数的包含上下文

matlab - 在Matlab中使用递归算法获得更多详细错误消息吗?

php - 如何在php错误日志中制作/引起php错误