【问题标题】:How to find and change the price of an item?如何查找和更改商品的价格?
【发布时间】: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


【解决方案1】:

我没有你程序的完整上下文,所以我只关注你的更改项目问题。

这个想法是使用dictionary数据结构,即key = item and value = price,

item_price = {}

while True:
    print(menu)
    selection = int(input("what menu do you want to select?"))
    if selection == 3:
        change = input('What item do you want to change the price for?')
        if change in item_price.keys():
            new_price = int(input('Write the new price: '))
            item_price[change] = new_price
            total = sum(item_price.values())
            print("Total: " + str(total))
        else:
            print("Item " + change + " not in the list.")
    elif selection == 2:
        newItem = input('What item do you want to add?')
        new_price = int(input('Write the new price: '))
        item_price[newItem] = new_price
        total = sum(item_price.values())
        print("Total: " + str(total))
    elif selection == 1:
        print(item_price)

您可能知道,一旦程序停止,您的所有数据都将消失,即您输入的数据不会被保存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多