所以我正在尝试编写一个Python代码,让您将商品添加到购物车中,然后一旦您输入“完成”,它就会将您添加到购物车中的每个商品的价格相加,然后告诉您总价。
我的问题是,一旦我输入“完成”,它只会添加我添加到购物车的最后一个商品的价格,然后将其打印出来。
shopping_cart = [""]
food = shopping_cart
#Stock
stock = {
"\nFruit\n\n"
"banana": 50,
"apple": 15,
"orange": 32,
"pear": 15,
"\nDrinks\n\n"
"apple juice": 10,
"orange juice": 10,
"pinapple juice": 10,
"milk": 15,
"\nSnacks\n\n"
"chips": 20,
"cookies": 20,
"chocolate": 25,
"lollies": 50
}
#Prices
prices = {
#Fruit
"banana": 10,
"apple": 5,
"orange": 5,
"pear": 5,
#Drinks
"apple juice": 5,
"orange juice": 5,
"pinapple juice": 5,
"milk": 4.80,
#Snacks
"chips": 7,
"cookies": 4,
"chocolate": 6,
"lollies": 5.50
}
#Loop
while True:
item = input("\nEnter an item: ").lower()
shopping_cart.append(item)
if item == 'done':
break
if item == 'cart':
print(shopping_cart)
if item == 'stock':
for k, v in stock.items():
print(k + ":", v)
#Define the bill variable
def shopping_bill(food):
total = 0
for key in prices:
for key in stock:
for item in food:
if item == key in prices:
total += prices[key]
break
print("Your bill total equals $", total)
print("Thank you for shopping at B&K Supermarket!")
shopping_bill(food)
最佳答案
这里有两个主要问题。第一个是在用户输入购物 list 之前将食物定义为 shopping_cart。因此,它仍然是一个空列表。
要解决此问题,请将 food = shopping_cart
移至 while True
循环之后,如下所示:
while True:
item = input("\nEnter an item: ").lower()
shopping_cart.append(item)
if item == 'done':
break
if item == 'cart':
print(shopping_cart)
if item == 'stock':
for k, v in stock.items():
print(k + ":", v)
food = shopping_cart
第二个问题是您要在字典顶部添加“\nFruit\n\n”和类似的内容。您需要将它们注释掉,这样代码就不会认为它们是字典的一部分。
stock = {
#fruit
"banana": 50,
"apple": 15,
"orange": 32,
"pear": 15,
#drinks
"apple juice": 10,
"orange juice": 10,
"pinapple juice": 10,
"milk": 15,
"chips": 20,
"cookies": 20,
"chocolate": 25,
"lollies": 50
}
将其输入提示并更改上面的代码
> banana
> apple
> done
产生
Your bill total equals $ 15
Thank you for shopping at B&K Supermarket!
关于python - 为什么我的 Python 代码只添加购物车中最后一件商品的价格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76360952/