简体   繁体   中英

How to modify the value for a key in a dictionary?

So I'm trying to create a program that can take an order, retrieve it from stock and output the cost. When I do so I get a price of all the items chosen in stock . Any help?

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")

Example Output:

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

I'd replace:

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

with:

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


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

Your compute_bill function should be implemented simply like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM