[英]How to modify the value for a key in a 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
我將替換為:
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]
您的compute_bill
函數應像下面這樣簡單地實現:
def compute_bill():
return prices[item_p] * quantity
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.