Menu
CoddyTech

보고서 생성

Coddy Python 여정의 논리와 흐름 섹션에 포함된 레슨. 78개 중 71번째.

challenge icon

챌린지

어려움

재고 관리 시스템에는 다음 구성 요소가 이미 구현되어 있습니다.

  1. 다음과 같은 전역 inventory 딕셔너리:
    • 키는 품목 이름(문자열)입니다.
    • 값은 다음 내용을 포함하는 딕셔너리입니다.
      • "price": 품목의 가격(float)
      • "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"

논리와 흐름의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러