항목 추가
Coddy GDScript 여정의 논리와 흐름 섹션에 포함된 레슨. 78개 중 72번째.
챌린지
쉬움add 명령을 추가하세요. 이전 단계에서 작성한 내용은 모두 그대로 유지하세요.
add Apple 0.5 100과 같은 줄은 가격이 0.5이고 재고가 100인 항목 Apple을 추가합니다. 항목 이름은 한 단어입니다.
먼저 _ready() 위에 함수 add_item(inventory, item, price, stock)를 작성하세요.
- 항목이 이미
inventory에 있으면Error: Item 'Apple' already exists.(항목 이름 포함)를 출력하고 아무것도 변경하지 않습니다. - 그렇지 않으면 항목 이름을 키로 하여
{"price": price, "stock": stock}을 저장하고Item 'Apple' added successfully.을 출력합니다.
그런 다음 루프에 add에 대한 elif 분기를 추가하세요. 함수를 호출하기 전에 줄을 확인하세요.
- 줄에 정확히
4개의 요소가 없으면Error: Use add ITEM PRICE STOCK를 출력합니다. - 가격이 숫자가 아니거나 재고가 정수가 아니면
Error: Price and stock must be numeric.을 출력합니다. - 그렇지 않으면 가격을
float으로, 재고를int로 변환하여add_item()을 호출합니다.
add Apple 0.5 100, add Banana 0.2 50, add Apple 0.6 30, show 및 exit 명령을 실행하면 다음과 같은 출력이 나옵니다.
Inventory Management System
Item 'Apple' added successfully.
Item 'Banana' added successfully.
Error: Item 'Apple' already exists.
{ "Apple": { "price": 0.5, "stock": 100 }, "Banana": { "price": 0.2, "stock": 50 } }
Goodbye!직접 해보기
extends Node
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)
else:
print("Unknown command")
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러