재고 업데이트
Coddy Python 여정의 Logic & Flow 섹션에 포함된 레슨 — 78개 중 69번째.
챌린지
쉬움item (문자열)과 quantity (정수)라는 두 개의 인자를 받는 update_stock이라는 이름의 함수를 생성하세요. 이 함수는 다음을 수행해야 합니다:
inventory딕셔너리에 해당 항목이 존재하는지 확인합니다.- 존재하지 않는 경우,
"Error: Item '<item>' not found."를 출력합니다.
- 존재하지 않는 경우,
- 항목이 존재하는 경우, 현재 재고에
quantity를 더하여 새로운 재고를 계산합니다.- 새로운 재고가 음수이면,
"Error: Insufficient stock for '<item>'."를 출력하고 업데이트를 수행하지 않습니다. - 그렇지 않으면,
inventory의 재고를 업데이트합니다.
- 새로운 재고가 음수이면,
"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)