Menu
CoddyTech

Add Item

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 72 of 78.

challenge icon

Challenge

Easy

Add 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():

  1. If the item is already in inventory, print Error: Item 'Apple' already exists. (with the item name) and change nothing
  2. Otherwise, store {"price": price, "stock": stock} under the item name and print Item '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 4 parts, print Error: 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 a float and the stock to an int

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

Practice on your own: Online GDScript compiler