2 回答

TA貢獻1816條經驗 獲得超6個贊
這里不需要一個函數,沒有它就可以輕松完成。
stock ={
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
shopping_cart = ["pear", "orange", "apple"]
shopping_cart = [("pear",1), ("orange", 3), ("apple",10)]
for i in shopping_cart:
if stock[i[0]] - i[1] < 0:
shopping_cart.pop(shopping_cart.index(i))
else:
stock[i[0]] -= i[1]
print("----------------")
print(" Bill")
print("----------------")
for i in shopping_cart:
print(f"{i[0]} x{i[1]} @ £{prices[i[0]]}")
print("----------------")
print(sum([prices[i[0]] * i[1] for i in shopping_cart]))
print("----------------")
解釋:
購物車
由元組組成
第一個元素 it 項目
第二是金額
第一個 for 循環
檢查是否有足夠的庫存來購買該商品,如果有,則從庫存中刪除該金額并繼續進行
如果沒有,它會從購物車中刪除該商品(是的,您可以修改它,當庫存不足但庫存> 0時,您可以向用戶出售剩余庫存。)
第二個for循環
使用 f 字符串格式化輸出
sum(列表理解)
輕松獲得商品價格*購買金額之和!

TA貢獻1831條經驗 獲得超4個贊
您可以使該函數compute_bill返回當前商品、價格,并檢查該商品是否有庫存。如果可以的話,減少數量。
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def compute_bill(shopping_list):
for item in shopping_list:
if stock.get(item, 0) > 0:
yield item, prices.get(item, 0),
stock[item] -= 1
shopping_list = ["pear", "orange", "apple"]
print("Items Purchased")
print("---------------")
total = 0
for item, value in compute_bill(shopping_list):
print('{:<10} @{}'.format(item.title(), value))
total += value
print("---------------")
print("Total: £{:.2f}".format(total))
印刷:
Items Purchased
---------------
Pear @3
Orange @1.5
---------------
Total: £4.50
添加回答
舉報