【发布时间】:2021-12-28 14:27:40
【问题描述】:
我正在编写一个程序来模拟某人在杂货店购物。我正在显示所有产品和价格,并提示用户输入他们购买的所有产品,用逗号分隔。我希望程序检查输入是否在产品字典中,并使用循环将其添加到购物车中。在将其添加到购物车之前,程序需要检查输入是否有效,这意味着该项目是否在要购买的产品列表中。当用户选择要购买的商品时,我希望程序询问用户该商品的数量,以及他们想要购买的商品数量。在 samThen 程序将计算所有产品的总和,然后计算税值,占总数的 24%,然后返回一个包含税的小计。这是我目前所拥有的:
def calculatetotal(slist, produce):
# for each item on the shoping list look up the cost & calculate total price
item_price = 0
subtotal = 0
VAT = 0
final_total = 0
basket = {}
for item in slist:
item_price = produce.get(item)
basket[item] = item_price
subtotal = subtotal + item_price
basket["Subtotal"] = subtotal
#calculating VAT
VAT = subtotal * 0.24
basket["VAT"] = VAT
#calculating price with tax
final_total = subtotal + VAT
basket["Total"] = final_total
# print off results
return basket
def main():
# set up grocery list with prices
produce={"Rice":5.00, "Bread":2.00, "Sugar":1.5, "Apple":0.75, "Cereal":3.75, "Gum": 1.00, "Water": 1.75, "Soda": 2.00}
# process input from the user - get a shopping list
item = input("Please enter the items that you want to buy: ")
slist = []
while(item != 'stop'):
if not (item in slist):
slist.append(item)
item = input("Please enter the items that you want to buy: ")
result = calculatetotal(slist, produce)
print(result)
main()
我已经得到了大部分,但是我上面提到的一些小改动,我不知道该怎么做。我忘了提到询问物品的数量并检查用户输入是否必须通过循环来完成。非常感谢任何输入。请显示代码的更改。提前谢谢你。
【问题讨论】:
标签: python arrays python-3.x list dictionary