Почему Elif печатает после некоторых входов в список? - PullRequest
0 голосов
/ 17 июня 2019

Итак, я кодирую корзину для покупок и печатает выписку 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)) 

вывод не должен показывать "пожалуйста, введите верный элемент", он должен просто добавить этот элемент и запросить другой ввод.

Ответы [ 2 ]

4 голосов
/ 17 июня 2019

elif относится только к последнему if перед ним. Вы хотите изменить все if на 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 может быть:

    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))
1 голос
/ 17 июня 2019

Независимо от вашей конкретной логики (которая решает, решит ли ваша проблема или нет), вы, вероятно, неправильно используете оператор 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.

Моя личная заметка : поскольку у вас уже есть список элементов, вы можете просто создать словарь названий продуктов длякоэффициенты , поэтому весь материал будет сведен к поиску в словаре, который, на мой взгляд, более удобен, чем жесткое кодирование значений в методе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...