【发布时间】:2022-12-19 19:21:22
【问题描述】:
我在字典中写了一个餐厅菜单,有 4 个选项,允许用户输入他/她的预算,然后将项目添加到他/她的购物车中。如果用户输入选项 3,那么他/她可以更改他/她在购物车中的商品价格,方法是写下商品名称,然后输入新价格。我遇到了问题编写代码来查找商品并相应地更改其价格。我写了下面的代码,它只是改变了最新商品的价格,而不是用户输入的价格。感谢任何 cmets/指南。
menu = {
1: 'Print ou the menu',
2: 'add Item and its price',
3: 'Change the price of an item in your cart'
}
money = int(input('How much is your budget? '))
category_n = [] #store all the items
sum_all_item = [] # store the price of the items
total = 0
while True:
menu()
if selection == 3:
change = input('What item do you want to change the price for?')
if change in category_n:
sum_all_item.remove(price_of_item) #it changes the price of the latest item
money = money + price_of_item
total -= price_of_item
new_price = int(input('Write the new price: '))
sum_all_item.append(new_price)
money = money - new_price
total +=new_price
【问题讨论】:
-
在您的代码中,我没有看到它在您的购物车中找到商品的部分,我相信这就是它找不到该商品的原因。
-
从学习字典数据结构开始,用它来创建产品和价格列表,products = {'bread': 2.00, 'fruit': 6.0, 'pet': 9.0} productsk[productToChangeInput] = updt_price_from_user,伪代码, 详情在这里, realpython.com/iterate-through-dictionary-python
-
您显示的代码似乎都没有使用字典,唯一的数据结构看起来是
sum_all_item尽管它的名字暗示它是一个总和,但它似乎是一个列表。我不清楚该列表的真正目的是什么,或者您希望更改后的价格出现在哪里。您能否提供更多代码,显示价格的定义位置?在您的代码中唯一看起来像价格的东西是price_of_item,这大概是已经专门针对给定商品查找的东西。 -
@Blckknght 是的。我刚刚添加了它。 category_n 是一个存储项目的列表,sum_all_item 存储每个项目的价格。然后我使用 tabulate 以表格形式将它们打印出来
标签: python python-3.x