检查库存是否充足
本课属于 Coddy Python 学习旅程的“逻辑与流程”单元。第 70 课,共 78 课。
挑战
简单创建一个名为 check_availability 的函数,它接受一个参数:item(字符串)。该函数应:
- 检查
inventory字典中是否存在该商品。- 如果不存在,则返回
"Item not found"。
- 如果不存在,则返回
- 如果该商品存在,则返回该商品的当前库存。
在代码底部添加(替换为)以下代码块:
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"亲手试试
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.")
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) 逻辑与流程中的所有课
自己练习: Python 在线编译器