如何允许用户输入字典中包含的特定项目的多个数字

问题描述 投票:0回答:1

在计算机科学入门课程中,这是非常基本的代码,应该保持不变。我的任务是创建一台具有各种功能的自动售货机,其中我所坚持的两个功能是允许用户在自动售货机中输入多个商品,即:用户输入他们想要 2 支口红而不是 1 支。第二个问题是创建代码来计算购物车的总额,同时还计算他们获得了多少特定商品,例如如果他们购买了 2 支口红和 1 支眼影而不是 10 美元,那么他们的购物车总计为 18 美元(我希望这是有道理的) 。我的代码到目前为止可以工作,我还没有完成输入菜单,但我觉得我需要先解决这两个问题,然后才能继续为选项 d (结帐)创建下一个 else 语句


makeup_cart = []

makeup = {'lipstick': 8.00, 'highlight': 9.00, 'eyeshadow': 2.00, 'foundation':11.00, 'eyeliner':5.00, 'bronzer':7.00, 'lipliner':7.00,'blush':5.00, 'mascara':8.00, 'lipgloss  ': 4.00 }

while True:
        print("\nMenu:")
        print("a = Display makeup list and prices")
        print("b = Add a makeup item to cart")
        print("c = View cart")
        print("d = Checkout")
        print("e = Exit")

        choice = input("Enter your choice (a-e): ")

        if choice == "a":
            print(makeup) # prints makeup dictionary
        elif choice == "b":
            item = input("Enter a makeup from the menu item to add: ") #prompts user to input for makeup to add to cart 
            makeup_cart.append(item) #adds item to cart
            print(f"your {item} has been added to the cart  ") 
            print (makeup_cart) # prints current cart
        elif choice == "c":
            if makeup_cart:
              print("Makeup Cart:")
              for item in makeup_cart: #prints items the user added into the cart as a list of items 
                print( item)
        else:
          print("The makeup cart is empty") # if user hasnt added anything then the cart will come up empty 
      

我正在考虑创建另一个字典并使用 count+=1 以便程序考虑用户想要的产品数量。我的下一步是为选项 d 创建另一个 else 语句,它是 checkout,这就是第二个问题出现的地方,即如何计算总数。

python list function dictionary
1个回答
0
投票

要计算用户想要的项目数量,您可以使用:

    len(makeup)

计算总价:

    elif choice=="c":
         sum=0
         for k,v in makeup.items():
             sum+=v
             print(sum)

k 和 v 在 for 语句中自动分配为键和值, 这将在结账时给出总价。

还有一个建议,在 elif 语句中使用 choice.lower() 使其更加通用

© www.soinside.com 2019 - 2024. All rights reserved.