보고서 생성
Coddy GDScript 여정의 논리와 흐름 섹션에 포함된 레슨. 78개 중 75번째.
챌린지
어려움마지막으로, 여러 항목을 한 번에 판매하고 수익을 보고하는 sell 명령을 추가하세요. 이전 단계에서 작성한 내용은 모두 유지하세요.
sell Apple:30 Banana:20과 같은 한 줄은 사과 30개와 바나나 20개를 판매합니다. sell 뒤의 각 부분은 항목 이름, 콜론, 수량으로 이루어지며, 한 항목은 한 줄에 최대 한 번만 나타납니다.
_ready() 위에 sales_report(inventory, sales) 함수를 작성하세요. sales는 각 항목 이름을 판매 수량에 대응시키는 딕셔너리입니다. 각 항목에 대해 순서대로 다음을 수행하세요.
- 항목이
inventory에 없으면Error: Item 'Orange' not found.을 출력하고 다음 항목으로 넘어갑니다. - 재고가 수량보다 적으면
Error: Insufficient stock for 'Apple'.을 출력하고 다음 항목으로 넘어갑니다. - 그렇지 않으면 재고에서 해당 수량을 빼고, 수량에 가격을 곱한 값을 수익에 더합니다.
함수는 Total revenue: $ 뒤에 소수점 이하 두 자리로 표시한 수익을 붙인 텍스트를 반환합니다.
반복문에서 sell 분기는 명령 뒤에 오는 부분들로 sales 딕셔너리를 만듭니다. 콜론 :으로 구분된 이름과 정수가 아닌 부분이 있으면 Error: Invalid sale 'Apple-3'.을 출력하고(해당 부분을 사용하여) 건너뜁니다. 그런 다음 sales_report()가 반환하는 값을 출력하세요.
add Apple 0.5 50, add Banana 0.2 60, sell Apple:30 Banana:20 Orange:10, show, exit 명령을 실행하면 출력은 다음과 같습니다.
Inventory Management System
Item 'Apple' added successfully.
Item 'Banana' added successfully.
Error: Item 'Orange' not found.
Total revenue: $19.00
{ "Apple": { "price": 0.5, "stock": 20 }, "Banana": { "price": 0.2, "stock": 40 } }
Goodbye!직접 해보기
extends Node
func add_item(inventory: Dictionary, item: String, price: float, stock: int) -> void:
if inventory.has(item):
print("Error: Item '%s' already exists." % item)
return
inventory[item] = {"price": price, "stock": stock}
print("Item '%s' added successfully." % item)
func update_stock(inventory: Dictionary, item: String, quantity: int) -> void:
if not inventory.has(item):
print("Error: Item '%s' not found." % item)
return
var new_stock: int = inventory[item]["stock"] + quantity
if new_stock < 0:
print("Error: Insufficient stock for '%s'." % item)
return
inventory[item]["stock"] = new_stock
print("Stock for '%s' updated successfully." % item)
func check_availability(inventory: Dictionary, item: String) -> int:
if not inventory.has(item):
return -1
return inventory[item]["stock"]
func _ready():
# 재고 목록: 품목 이름 -> {"price": float, "stock": int}
var inventory := {}
print("Inventory Management System")
while true:
var line := OS.read_string_from_stdin()
var parts := line.split(" ")
var command := parts[0]
if command == "exit":
print("Goodbye!")
break
elif command == "show":
print(inventory)
elif command == "add":
if parts.size() != 4:
print("Error: Use add ITEM PRICE STOCK")
elif not parts[2].is_valid_float() or not parts[3].is_valid_int():
print("Error: Price and stock must be numeric.")
else:
add_item(inventory, parts[1], float(parts[2]), int(parts[3]))
elif command == "update":
if parts.size() != 3:
print("Error: Use update ITEM QUANTITY")
elif not parts[2].is_valid_int():
print("Error: Quantity must be an integer.")
else:
update_stock(inventory, parts[1], int(parts[2]))
elif command == "check":
if parts.size() != 2:
print("Error: Use check ITEM")
else:
var stock := check_availability(inventory, parts[1])
if stock == -1:
print("Item not found")
else:
print(parts[1], ": ", stock, " in stock")
else:
print("Unknown command")
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러