Menu
Coddy logo textTech

Actualizar stock

Parte de la sección Logic & Flow del Journey de Python de Coddy — lección 69 de 78.

challenge icon

Desafío

Fácil

Crea una función llamada update_stock que reciba dos argumentos: item (string) y quantity (int). La función debe:

  1. Comprobar si el artículo existe en el diccionario inventory.
    • Si no existe, imprimir "Error: Item '<item>' not found.".
  2. Si el artículo existe, calcular el nuevo stock sumando la quantity al stock actual.
    • Si el nuevo stock es negativo, imprimir "Error: Insufficient stock for '<item>'." y no actualizar.
    • De lo contrario, actualizar el stock en el inventory.
  3. Imprimir "Stock for '<item>' updated successfully.".

Añade (reemplaza) el siguiente bloque de código al final de tu código:

add_item("Apple", 0.5, 100)
add_item("Banana", 0.2, 50)
add_item("Apple", 0.6, 30)  # Should print an error
update_stock("Apple", -20)
update_stock("Banana", 30)
update_stock("Orange", 10)  # Should print an error
update_stock("Apple", -90)
print(inventory)  

Pruébalo tú mismo

inventory = {}

def add_item(item, price, stock):
    if item in inventory:
        print(f"Error: Item '{item}' already exists.")
        return
    try:
        inventory[item] = {"price": float(price), "stock": int(stock)}
        print(f"Item '{item}' added successfully.")
    except ValueError:
        print("Error: Price and stock must be numeric.")


add_item("Apple", 0.5, 100)
add_item("Banana", 0.2, 50)
add_item("Apple", 0.6, 30)  # Should print an error
print(inventory)  

Todas las lecciones de Logic & Flow