【问题标题】:Why is Elif printning after some list inputs?为什么 Elif 在一些列表输入后打印?
【发布时间】:2019-10-30 22:17:59
【问题描述】:

因此,我编写了一个购物篮,并在输入一些项目后打印 elif 语句,例如“火腿”。为什么?

我已经尝试将 while 循环添加到项目列表中,但这没有奏效。

print("What would you like? We have:")
## A function to call anywhere throughout the code to be able to print 
the item list
def item_List():
    print(" - Milk")
    print(" - Bread")
    print(" - Butter")
    print(" - Salt")
    print(" - Pepper")
    print(" - Ham")
    print(" - Steak")
    print(" - Banana Bunch")
    print(" - Apple Tray")
    print(" - Grapes")
    print(" - Winegums")
    print(" - Black Jacks")
    print(" - Sugar")
    print(" - Honey")
    print(" - Tea Bags")
    print(" - Coffee")

()
## Function caller
item_List()


## Variable set to a list for future appends
items = []

total = 0
addmore = True
while addmore == True:
    print("Add an item or type stop.")
    userInput = input()
    if userInput.lower() == "stop":
        addmore = False
    else:
        if userInput.lower() == "milk":
            total += 1.55
        if userInput.lower() == "bread":
            total += 1.82
        if userInput.lower() == "butter":
            total += 1.29
        if userInput.lower() == "salt":
            total += 1.20
        if userInput.lower() == "pepper":
            total += 1.20
        if userInput.lower() == "ham":
            total += 1.99
        if userInput.lower() == "steak":
            total += 3.99
        if userInput.lower() == "banana bunch":
            total += 2.25
        if userInput.lower() == "apple tray":
            total += 1.52
        if userInput.lower() == "grapes":
            total += 1.41
        if userInput.lower() == "winegums":
            total += 0.85
        if userInput.lower() == "black jacks":
            total += 0.85
        if userInput.lower() == "sugar":
            total += 2.95
        if userInput.lower() == "honey":
            total += 0.85
        if userInput.lower() == "tea":
            total += 2.85
        if userInput.lower() == "coffee":
            total += 3.05
        elif userInput not in items:
            print("Please enter a valid item.")

## List append for user to change their shopping basket by adding items 
to their basket
    items.append(userInput)
    print("Item added. Basket Total:","£",round(total,3))

## This prints the of their basket/list
print("\n--- Your Shopping List ---")
for i in items:
    print(i.title())

## This prints the total of their basket/list
print("Total: £"+str(total)) 

输出不应显示“请输入一个有效的项目”,它应该只是添加该项目并要求另一个输入。

【问题讨论】:

  • elif 仅适用于您的 last if 子句
  • items 是您的购物清单,而不是可用商品的清单。逻辑不正确。
  • 您的条件是“如果该商品不是咖啡,并且它不在您的购物篮中,则它是无效商品”。

标签: python if-statement


【解决方案1】:

无论您的特定逻辑如何(由您决定是否解决您的问题),您都可能错误地使用了 elif 运算符:

如果用户输入milk,则总数增加1.55

    if userInput.lower() == "milk":
        total += 1.55

根据上下文,如果用户输入bread,则将总数增加1.82

    if userInput.lower() == "bread":
        total += 1.82

根据上下文,如果用户输入butter,则将总数增加1.29

    if userInput.lower() == "butter":
        total += 1.29

以此类推...直到最后一个: 根据上下文,如果用户输入coffee,则将总数增加 3.05

    if userInput.lower() == "coffee":
        total += 3.05

根据上下文,如果用户没有输入coffee 并且用户输入的内容不包含在items列表中,则写Please enter a valid item.

    elif userInput not in items:
        print("Please enter a valid item.")

最后一个检查是多余的,因为您已经检查过它们。 当用户输入一个字符串时,您需要检查一组不重叠的值(牛奶、面包等),您应该将所有的 if 转换为 elif,如下所示:

    if userInput.lower() == "milk":
        total += 1.55
    elif userInput.lower() == "bread":
        total += 1.82
    elif userInput.lower() == "butter":
        total += 1.29
    elif userInput.lower() == "salt":
        total += 1.20
    elif userInput.lower() == "pepper":
        total += 1.20
    elif userInput.lower() == "ham":
        total += 1.99
    elif userInput.lower() == "steak":
        total += 3.99
    elif userInput.lower() == "banana bunch":
        total += 2.25
    elif userInput.lower() == "apple tray":
        total += 1.52
    elif userInput.lower() == "grapes":
        total += 1.41
    elif userInput.lower() == "winegums":
        total += 0.85
    elif userInput.lower() == "black jacks":
        total += 0.85
    elif userInput.lower() == "sugar":
        total += 2.95
    elif userInput.lower() == "honey":
        total += 0.85
    elif userInput.lower() == "tea":
        total += 2.85
    elif userInput.lower() == "coffee":
        total += 3.05
    else
        print("Please enter a valid item.")

switch 语句的本质是什么。

我的个人笔记:由于您已经有一个元素列表,您可以创建一个产品名称到系数的字典,因此,整个东西都会减少在字典中查找,在我看来,这比在方法中硬编码值更易于维护。

【讨论】:

    【解决方案2】:

    elif 仅与它之前的最后一个 if 相关。您可能希望将所有ifs 更改为elif(当然第一个除外)。

    我个人喜欢使用字典来实现这种开关格式。我会创建一个包含所有可用商品及其价格的字典。

    items = {"milk": 1.55, "bread": 1.82, "butter": 1.29, "salt": 1.2, "pepper": 1.2, "ham": 1.99, "steak": 3.99, "banana bunch": 2.25, "apple tray": 1.52, "grapes": 1.41, "winegums": 0.85}
    

    现在item_List 函数可以更短:

        def item_List(items):
            for item in items:
                print("- {}".format(item.title()))
    

    while 循环的 else 部分可以是:

        try:
            cost = items[uerInput.lower()]
            total += cost
        except KeyError:
            print("Please enter a valid item.")
    

    您的整个代码已简化:

        items = {"milk": 1.55, "bread": 1.82, "butter": 1.29, "salt": 1.2} # etc...
    
        print("What would you like? We have:")
    
        for item in items:
            print("- {}".format(item.title()))
    
        shopping_list = []
        total = 0
        while:
            print("Add an item or type stop.")
            userInput = input()
            if userInput.lower() == "stop":
                break
    
            try:
                cost = items[uerInput.lower()]
                total += cost
                shopping_list.append(userInput)
                print("Item added. Basket Total:","£",round(total,3))
            except KeyError:
                print("Please enter a valid item.")
    
        ## This prints the items in their basket
        print("\n--- Your Shopping List ---")
        for i in shopping_list:
            print(i.title())
    
        ## This prints the total of their basket
        print("Total: £"+str(total))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2011-08-07
      相关资源
      最近更新 更多