【问题标题】:Making a shopping cart in Python用 Python 制作购物车
【发布时间】:2011-03-29 17:16:52
【问题描述】:

我正在学习 Python,并且正在尝试制作购物车(用于练习)。但我有点卡在这里:

# Vars
budget = 200; # Budget
total = 0; # Total price
prices = { # Price list
    "cola":22,
    "chips":18,
    "headset":800,
    "pencil":5
}
cart = [] # Shopping cart

while True:
    cmd = raw_input("Enter command: ");
    if cmd == "additem":

在 while 循环(特别是“if cmd ==”additem”)中,我希望用户输入商品的名称(来自价格字典),然后将其添加到购物车中。但是,我不是确定如何去做。

【问题讨论】:

  • 对我来说听起来像是一个家庭作业问题:),你到底卡在哪里了?你不知道如何从用户那里得到输入吗?您是否希望通过 shell 从命令行执行此操作?

标签: python dictionary shopping-cart


【解决方案1】:

家庭作业?

您的数据结构有点奇怪。您可能希望购物车是元组或其他内容的列表,每个元组是项目、数量,甚至是项目、数量、小计。但是。

if cmd == "additem":
    item = raw_input("Enter item name: ")
    cart.append(item)

#at the end
for item in cart:
    print "Item: %s. Price: %s" % (item, prices[item])

【讨论】:

    【解决方案2】:
    # Vars
    budget = 200; # Budget
    total = 0; # Total price
    prices = { # Price list
        "cola":22,
        "chips":18,
        "headset":800,
        "pencil":5
    }
    cart = [] # Shopping cart
    
    input = ['']
    while input[0] != 'quit':
        input = raw_input("Enter command: ").split()
        if input[0] == 'additem' and input[1] in prices:
            cart.append(input[1])
    

    【讨论】:

      【解决方案3】:
      # Vars
      budget = 200; # Budget
      total = 0; # Total price
      prices = { # Price list
          "cola":22,
          "chips":18,
          "headset":800,
          "pencil":5
      }
      cart = [] # Shopping cart
      cmd = raw_input("""
      ====Item=====Price====
      
          cola    :  22 $
          chips   :  18 $
          headset : 800 $
          pencil  :   5 $
      
      Enter order:""")
      while cmd in prices.keys():
          cart+=[(cmd,prices[cmd])]
          cmd = raw_input("Enter order: ")
      
      if cmd not in ["","\t","\n"]:
          print cmd," is not available",
      
      print"you cart contains :\n"
      if cart != []:
          for item in cart:
              print item[0],"\t:",item[1]," $"
      else:
          print "Nothing"
      
      raw_input("\nPress enter to exit...")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多