Menu
Coddy logo textTech

在庫の更新

CoddyのPythonジャーニー「Logic & Flow」セクションの一部 — レッスン 69/78。

challenge icon

チャレンジ

簡単

update_stock という名前の関数を作成してください。この関数は、item(文字列)と quantity(整数)の2つの引数を取ります。この関数は以下の処理を行う必要があります。

  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)  # エラーが出力されるはずです
update_stock("Apple", -20)
update_stock("Banana", 30)
update_stock("Orange", 10)  # エラーが出力されるはずです
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)  

Logic & Flowのすべてのレッスン