Add Item
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 72 of 78.
Challenge
EasyAdd the command add. Keep everything you wrote in the previous step.
A line like add Apple 0.5 100 adds the item Apple with the price 0.5 and a stock of 100. Item names are one word.
First, write the function add_item(inventory, item, price, stock) above _ready():
- If the item is already in
inventory, printError: Item 'Apple' already exists.(with the item name) and change nothing - Otherwise, store
{"price": price, "stock": stock}under the item name and printItem 'Apple' added successfully.
Then add an elif branch for add in the loop. Check the line before you call the function:
- If the line does not have exactly
4parts, printError: Use add ITEM PRICE STOCK - If the price is not a number or the stock is not a whole number, print
Error: Price and stock must be numeric. - Otherwise, call
add_item()with the price converted to afloatand the stock to anint
For the commands add Apple 0.5 100, add Banana 0.2 50, add Apple 0.6 30, show and exit, the output is:
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!Try it yourself
extends Node
func _ready():
# The inventory: item name -> {"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")
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler