Menu
Coddy logo textTech

재고 확인

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

challenge icon

챌린지

쉬움

하나의 인자 item (문자열)을 받는 check_availability라는 이름의 함수를 만드세요. 이 함수는 다음을 수행해야 합니다:

  1. inventory 딕셔너리에 해당 항목이 존재하는지 확인합니다.
    • 존재하지 않는 경우, "Item not found"를 반환합니다.
  2. 항목이 존재하는 경우, 해당 항목의 현재 재고를 반환합니다.

코드의 맨 아래에 다음 코드 블록을 추가(또는 교체)하세요:

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"

직접 해보기

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.")


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)  

Logic & Flow의 모든 레슨