Menu
CoddyTech

Actualizar existencias

Parte de la sección Lógica y flujo del Journey de GDScript de Coddy. Lección 73 de 78.

challenge icon

Desafío

Fácil

Añade el comando update. Conserva todo lo que escribiste en los pasos anteriores.

Una línea como update Apple -20 suma -20 al inventario de Apple: una cantidad positiva es una entrega; una negativa retira artículos.

Escribe la función update_stock(inventory, item, quantity) encima de _ready():

  1. Si el artículo no está en inventory, imprime Error: Item 'Orange' not found. (con el nombre del artículo)
  2. Si el nuevo inventario sería negativo, imprime Error: Insufficient stock for 'Apple'. y conserva el inventario anterior
  3. De lo contrario, guarda el nuevo inventario e imprime Stock for 'Apple' updated successfully.

En el bucle, añade una rama elif para update:

  • Si la línea no tiene exactamente 3 partes, imprime Error: Use update ITEM QUANTITY
  • Si la cantidad no es un número entero, imprime Error: Quantity must be an integer.
  • De lo contrario, llama a update_stock()

Para los comandos 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 y exit, la salida es:

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!

Pruébalo tú mismo

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():
	# El inventario: nombre del artículo -> {"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")

Todas las lecciones de Lógica y flujo

Practica por tu cuenta: Compilador de GDScript online