在庫状況の確認
CoddyのPythonジャーニー「Logic & Flow」セクションの一部 — レッスン 70/78。
チャレンジ
簡単1つの引数 item (文字列) を受け取る check_availability という名前の関数を作成してください。この関数は以下の処理を行う必要があります:
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)