Menu
Coddy logo textTech

Atualizar Estoque

Parte da seção Logic & Flow do Journey de Python da Coddy — lição 69 de 78.

challenge icon

Desafio

Fácil

Crie uma função chamada update_stock que recebe dois argumentos: item (string) e quantity (int). A função deve:

  1. Verificar se o item existe no dicionário inventory.
    • Se não existir, imprima "Error: Item '<item>' not found.".
  2. Se o item existir, calcule o novo estoque somando a quantity ao estoque atual.
    • Se o novo estoque for negativo, imprima "Error: Insufficient stock for '<item>'." e não atualize.
    • Caso contrário, atualize o estoque no inventory.
  3. Imprima "Stock for '<item>' updated successfully.".

Adicione (substitua) o seguinte bloco de código ao final do seu 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)  

Experimente você mesmo

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 as lições de Logic & Flow