首页 > 解决方案 > 为什么 Elif 在一些列表输入后打印?

问题描述

因此,我对购物篮进行编码,并在输入一些项目后打印 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)) 

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

标签: pythonif-statement

解决方案


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

推荐阅读