Menu
Coddy logo textTech

보고서 생성

Coddy Python 여정의 Logic & Flow 섹션에 포함된 레슨 — 78개 중 71번째.

challenge icon

챌린지

어려움

재고 시스템에는 이미 다음과 같은 구성 요소가 구현되어 있습니다:

  1. 다음과 같은 전역 inventory 딕셔너리:
    • 키는 아이템 이름 (문자열)
    • 값은 다음을 포함하는 딕셔너리:
      • "price": 아이템의 가격 (float)
      • "stock": 현재 재고 수량 (integer)
  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의 모든 레슨