Menu
CoddyTech

更新库存

本课属于 Coddy Python 学习旅程的“逻辑与流程”单元。第 69 课,共 78 课。

challenge icon

挑战

简单

创建一个名为 update_stock 的函数,它接受两个参数:item(字符串)和 quantity(整数)。函数应执行以下操作:

  1. 检查 inventory 字典中是否存在该商品。
    • 如果不存在,则打印 "Error: Item '<item>' not found."。
  2. 如果该商品存在,则将 quantity 加到当前库存上,计算新的库存。
    • 如果新库存为负数,则打印 "Error: Insufficient stock for '<item>'.",且不更新库存。
    • 否则,更新 inventory 中的库存。
  3. 打印 "Stock for '<item>' updated successfully."。

在代码末尾添加(替换为)以下代码块:

add_item("Apple", 0.5, 100)
add_item("Banana", 0.2, 50)
add_item("Apple", 0.6, 30)  # Should print an error
update_stock("Apple", -20)
update_stock("Banana", 30)
update_stock("Orange", 10)  # Should print an error
update_stock("Apple", -90)
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.")


add_item("Apple", 0.5, 100)
add_item("Banana", 0.2, 50)
add_item("Apple", 0.6, 30)  # Should print an error
print(inventory)  

逻辑与流程中的所有课

自己练习: Python 在线编译器