用Python制作购物车

2 投票
3 回答
5540 浏览
提问于 2025-04-16 14:40

我正在学习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":

在这个循环里(特别是“如果命令是‘additem’”这部分),我希望用户输入一个商品的名字(这个名字要从价格字典里找),然后把这个商品添加到购物车里。不过,我不太确定该怎么做。

3 个回答

1
# 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...")

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

1
# 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

作业吗?

你的数据结构有点奇怪。你可能想把购物车设计成一个元组的列表,每个元组可以包含商品、数量,或者甚至是商品、数量、小计。不过。

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

撰写回答