如何修改字典中键的值?

时间:2018-02-09 17:35:32

标签: python python-3.x dictionary

所以我正在尝试创建一个可以接受订单的程序,从stock检索它并输出成本。当我这样做时,我得到stock中选择的所有项目的价格。有什么帮助吗?

import time 

def compute_bill(component):
    total = 0
    for item in component:
        total += prices[item_p]
    return total

def localTime():
    localtime = time.asctime(time.localtime(time.time()))
    return localtime

stock = {
    "I7": 2,
    "Keyboard": 3,
    "Mouse": 2,
    "GPU": 4
}
prices = {
    "I7": 250,
    "Keyboard": 15,
    "Mouse": 12,
    "GPU": 350
}
item_p = ''
item_p = input("Please input the item you would like: ")
quantity = int(input("Please input the quantity you would like: "))

if item_p in stock:
    print("X ordered a ", item_p,"at", localTime()," Which comes to a total of £", compute_bill(item_p))
else:
    print("Error")

示例输出:

Please input the item you would like:  Keyboard
X ordered a  Keyboard at Fri Feb  9 17:16:09 2018  Which comes to a total of £ 120

2 个答案:

答案 0 :(得分:1)

我会替换:

def compute_bill(component):
    total = 0
    for item in component:
        total += prices[item_p]
    return total

使用:

def update_stock(component):
    global stock
    stock[component] -= quantity


def compute_bill(component):
    update_stock(component)
    return quantity * prices[component]

答案 1 :(得分:0)

您的compute_bill功能应该像这样实现:

def compute_bill():
    return prices[item_p] * quantity