Menu
CoddyTech

Update Stock

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

challenge icon

Challenge

Easy

Add the command update. Keep everything you wrote in the previous steps.

A line like update Apple -20 adds -20 to the stock of Apple: a positive quantity is a delivery, a negative one takes items out.

Write the function update_stock(inventory, item, quantity) above _ready():

  1. If the item is not in inventory, print Error: Item 'Orange' not found. (with the item name)
  2. If the new stock would be negative, print Error: Insufficient stock for 'Apple'. and keep the old stock
  3. Otherwise, store the new stock and print Stock for 'Apple' updated successfully.

In the loop, add an elif branch for update:

  • If the line does not have exactly 3 parts, print Error: Use update ITEM QUANTITY
  • If the quantity is not a whole number, print Error: Quantity must be an integer.
  • Otherwise, call update_stock()

For the commands add Apple 0.5 100, add Banana 0.2 50, add Apple 0.6 30, update Apple -20, update Banana 30, update Orange 10, update Apple -90, show and exit, the output is:

Inventory Management System
Item 'Apple' added successfully.
Item 'Banana' added successfully.
Error: Item 'Apple' already exists.
Stock for 'Apple' updated successfully.
Stock for 'Banana' updated successfully.
Error: Item 'Orange' not found.
Error: Insufficient stock for 'Apple'.
{ "Apple": { "price": 0.5, "stock": 80 }, "Banana": { "price": 0.2, "stock": 80 } }
Goodbye!

Try it yourself

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 _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)
		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]))
		else:
			print("Unknown command")

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler