Menu
Coddy logo textTech

レポートの生成

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

challenge icon

チャレンジ

難しい

在庫管理システムには、すでに以下のコンポーネントが実装されています:

  1. グローバルな inventory 辞書:
    • キーはアイテム名(文字列)
    • 値は以下の内容を含む辞書:
      • "price":アイテムの価格(浮動小数点数)
      • "stock":現在の在庫数(整数)
  2. 新しいアイテムを在庫に追加する add_item(item, price, stock) 関数
  3. 在庫レベルを更新する update_stock(item, quantity) 関数
  4. 現在の在庫レベルを返す check_availability(item) 関数

あなたのタスクは、以下の処理を行う sales_report(sales) 関数を実装することです:

  1. 以下の sales 辞書を受け取ります:
    • キーはアイテム名
    • 値は販売された数量
  2. 販売辞書内の各アイテムについて:
    • アイテムが在庫に存在するか確認する
    • 十分な在庫があるか確認する
    • 在庫レベルを減らして在庫を更新する
    • 価格と販売数量に基づいて収益を計算する
  3. 総収益を含むフォーマット済み文字列を返す

以下の特定のエラーを処理してください:

  • アイテムが在庫に存在しない場合は、次のように出力します:"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"

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