【问题标题】:How to check if a users input is valid against a list/tuple of pizzas?如何检查用户输入是否对披萨列表/元组有效?
【发布时间】:2018-10-06 23:00:47
【问题描述】:

很抱歉,如果以前有人问过这个问题,但我在其他问题中找不到确切的答案或足够接近的答案。我对 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

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

伊利亚斯。

【问题讨论】:

  • if selected_pizza in range(len(pizzas_with_prices)):
  • @Barmar 是对的,顺便说一句,在这种情况下,您似乎把事情复杂化了。考虑创建一个类,把你的变量和定义放到这个类中,避免使用全局变量。
  • 您还需要分别读取输入、验证输入,然后将其附加到selected_pizza 列表中。
  • 您可以使用argparse 模块来验证和处理用户输入。
  • @Barmar 我会将你在 selectFunction() 中编写的代码放在哪里。再次抱歉,我对 Python 还是很陌生

标签: python error-handling index-error


【解决方案1】:

据我了解,我会这样做。我创建了一个单独的函数来选择一个有效的比萨饼,然后添加到函数以选择许多比萨饼。

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)

希望对你有帮助。

【讨论】:

    【解决方案2】:

    读取输入,对其进行验证,然后将其添加到 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()

    【讨论】:

      猜你喜欢
      • 2014-06-30
      • 2014-08-08
      • 2016-05-09
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      相关资源
      最近更新 更多