生成报告
本课属于 Coddy Python 学习旅程的“逻辑与流程”单元。第 71 课,共 78 课。
挑战
困难库存系统已经实现了以下组件:
- 一个全局
inventory字典,其中:- 键是商品名称(字符串)
- 值是包含以下内容的字典:
"price":商品价格(浮点数)"stock":当前库存数量(整数)
- 一个
add_item(item, price, stock)函数,用于向库存中添加新商品 - 一个
update_stock(item, quantity)函数,用于更新库存数量 - 一个
check_availability(item)函数,用于返回当前库存数量
你的任务是实现 sales_report(sales) 函数,该函数需要:
- 接收一个
sales字典,其中:- 键是商品名称
- 值是已售出的数量
- 对于销售字典中的每件商品:
- 检查库存中是否存在该商品
- 检查库存是否充足
- 减少库存数量并更新库存
- 根据价格和售出数量计算收入
- 返回包含总收入的格式化字符串
处理以下特定错误:
- 如果库存中不存在某件商品,则打印:
"Error: Item '{item}' not found." - 如果库存不足,则打印:
"Error: Insufficient stock for '{item}'."
输出应为以下格式的字符串:“Total revenue: ${total:.2f}”
在代码底部添加(替换为)以下代码块:
add_item("Apple", 0.5, 50)
add_item("Banana", 0.2, 60)
sales = {"Apple": 30, "Banana": 20, "Orange": 10} # Orange should print an error
print(sales_report(sales)) # Should output: Total revenue: $19.00
print(inventory)亲手试试
inventory = {}
def add_item(item, price, stock):
if item in inventory:
print(f"Error: Item '{item}' already exists.")
return
try:
inventory[item] = {"price": float(price), "stock": int(stock)}
print(f"Item '{item}' added successfully.")
except ValueError:
print("Error: Price and stock must be numeric.")
def update_stock(item, quantity):
if item not in inventory:
print(f"Error: Item '{item}' not found.")
return
try:
new_stock = inventory[item]["stock"] + int(quantity)
if new_stock < 0:
print(f"Error: Insufficient stock for '{item}'.")
else:
inventory[item]["stock"] = new_stock
print(f"Stock for '{item}' updated successfully.")
except ValueError:
print("Error: Quantity must be an integer.")
def check_availability(item):
if item not in inventory:
return "Item not found"
return inventory[item]["stock"]
add_item("Apple", 0.5, 100)
add_item("Banana", 0.2, 50)
update_stock("Apple", -20)
update_stock("Banana", 30)
print(check_availability("Apple")) # Should return 80
print(check_availability("Banana")) # Should return 80
print(check_availability("Orange")) # Should return "Item not found"逻辑与流程中的所有课
自己练习: Python 在线编译器