Menu
CoddyTech

재고 업데이트

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

challenge icon

챌린지

쉬움

update_stock라는 함수를 만들고 두 개의 인수인 item(문자열)과 quantity(정수)를 받도록 하세요. 함수는 다음을 수행해야 합니다.

  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)  # 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)  

직접 해보기

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)  

논리와 흐름의 모든 레슨

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