我正在学习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“)我想让用户输入一个项目的名称(来自价格字典)然后将它添加到购物车中。但是,我不是确定如何解决这个问题。
答案 0 :(得分: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])
答案 1 :(得分: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])
答案 2 :(得分: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...")