재고 확인
Coddy Python 여정의 논리와 흐름 섹션에 포함된 레슨. 78개 중 70번째.
챌린지
쉬움check_availability라는 함수를 만들고, 인수 하나인 item(문자열)을 받도록 하세요. 함수는 다음을 수행해야 합니다.
- 항목이
inventory딕셔너리에 있는지 확인하세요.- 항목이 없으면
"Item not found"을 반환하세요.
- 항목이 없으면
- 항목이 있으면 해당 항목의 현재 재고를 반환하세요.
다음 코드 블록을 코드 맨 아래에 추가(교체)하세요.
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) 논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러