diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index 3e50ef8..6cf3c4e 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -41,18 +41,197 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "id": "cc2c441d-9dcf-4817-b097-cf6cbe440846", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Initial inventory: {'t-shirt': 5, 'mug': 55, 'hat': 5, 'book': 5, 'keychain': 5}\n", + "Please answer with 'yes' or 'no'.\n", + "\n", + "Customer Orders: {'mug'}\n", + "\n", + "Total different products ordered: 1\n", + "Percentage of products ordered: 20.00%\n", + "Updated Inventory:\n", + "t-shirt: 5\n", + "mug: 54\n", + "hat: 5\n", + "book: 5\n", + "keychain: 5\n", + "\n", + "Program finished. Thank you for using the system.\n" + ] + } + ], "source": [ - "# your code goes here" + "#incluir error handling en las funciones\n", + "products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n", + "\n", + "\n", + "def initialize_inventory(products):\n", + " \"\"\"\n", + " Pide al usuario el stock inicial de cada producto.\n", + " Maneja errores de conversión y valores negativos.\n", + " \"\"\"\n", + " if not isinstance(products, (list, tuple, set)):\n", + " raise TypeError(\"The products parameter must be a list, tuple or set.\")\n", + "\n", + " if not products:\n", + " raise ValueError(\"Product list cannot be empty.\")\n", + "\n", + " inventory = {}\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " quantity_str = input(f\"Enter the initial stock quantity for {product}: \")\n", + " quantity = int(quantity_str)\n", + "\n", + " if quantity < 0:\n", + " # No es un error de Python, pero lógicamente es inválido\n", + " raise ValueError(\"Quantity cannot be negative.\")\n", + " except ValueError as e:\n", + " print(f\"Invalid input for {product}: {e}. Please enter a non-negative integer.\")\n", + " else:\n", + " # Solo entra aquí si no ha habido excepción\n", + " inventory[product] = quantity\n", + " break\n", + " return inventory\n", + "\n", + "\n", + "def get_customer_orders(products):\n", + " \"\"\"\n", + " Recoge los pedidos del cliente. Solo se aceptan productos válidos.\n", + " \"\"\"\n", + " customer_order = set()\n", + "\n", + " while True:\n", + " try:\n", + " order = input(\n", + " \"Enter a product to order (t-shirt, mug, hat, book, keychain): \"\n", + " ).strip().lower()\n", + "\n", + " if not order:\n", + " raise ValueError(\"Empty input is not allowed.\")\n", + "\n", + " if order not in products:\n", + " # Forzamos error para tratarlo en el except\n", + " raise ValueError(f\"'{order}' is not a valid product.\")\n", + " except ValueError as e:\n", + " print(f\"Error: {e}\")\n", + " else:\n", + " customer_order.add(order)\n", + "\n", + " # Preguntar si quiere seguir pidiendo\n", + " while True:\n", + " more = input(\"Do you want to order another product? (yes/no): \").strip().lower()\n", + " if more == \"yes\":\n", + " break\n", + " elif more == \"no\":\n", + " return customer_order\n", + " else:\n", + " print(\"Please answer with 'yes' or 'no'.\")\n", + "\n", + "\n", + "def update_inventory(customer_orders, inventory):\n", + " \"\"\"\n", + " Actualiza el inventario restando 1 por cada producto pedido.\n", + " Usa raise para casos lógicos incorrectos pero los gestiona internamente.\n", + " \"\"\"\n", + " if not isinstance(inventory, dict):\n", + " raise TypeError(\"Inventory must be a dictionary.\")\n", + "\n", + " for order in customer_orders:\n", + " try:\n", + " if order not in inventory:\n", + " # Error lógico: se pide algo que no existe en el inventario\n", + " raise KeyError(f\"{order} is not present in the inventory.\")\n", + "\n", + " if inventory[order] <= 0:\n", + " # Sin stock\n", + " raise ValueError(f\"Sorry, {order} is out of stock.\")\n", + " except KeyError as e:\n", + " print(f\"Inventory error: {e}\")\n", + " except ValueError as e:\n", + " print(e)\n", + " else:\n", + " # Solo si no hubo excepción\n", + " inventory[order] -= 1\n", + "\n", + " return inventory\n", + "\n", + "\n", + "def calculate_order_statistics(customer_orders, products):\n", + " \"\"\"\n", + " Calcula:\n", + " - nº de productos distintos pedidos\n", + " - % de productos del catálogo que se han pedido al menos una vez\n", + " \"\"\"\n", + " if not isinstance(products, (list, tuple, set)) or len(products) == 0:\n", + " raise ValueError(\"Product list must be a non-empty list/tuple/set.\")\n", + "\n", + " total_products_ordered = len(customer_orders)\n", + " percent_ordered = (total_products_ordered / len(products)) * 100\n", + "\n", + " order_statistics = (total_products_ordered, percent_ordered)\n", + " return order_statistics\n", + "\n", + "\n", + "def print_order_statistics(order_statistics):\n", + " total_products_ordered, percent_ordered = order_statistics\n", + " print(f\"Total different products ordered: {total_products_ordered}\")\n", + " print(f\"Percentage of products ordered: {percent_ordered:.2f}%\")\n", + "\n", + "\n", + "def print_update_inventory(inventory):\n", + " print(\"Updated Inventory:\")\n", + " for product, quantity in inventory.items():\n", + " print(f\"{product}: {quantity}\")\n", + "\n", + "\n", + "def main():\n", + " try:\n", + " # 1) Inicializar inventario\n", + " inventory = initialize_inventory(products)\n", + " print(\"\\nInitial inventory:\", inventory)\n", + "\n", + " # 2) Obtener pedidos de cliente\n", + " customer_order = get_customer_orders(products)\n", + " print(\"\\nCustomer Orders:\", customer_order)\n", + "\n", + " # 3) Actualizar inventario\n", + " inventory = update_inventory(customer_order, inventory)\n", + "\n", + " # 4) Calcular estadísticas del pedido\n", + " order_stats = calculate_order_statistics(customer_order, products)\n", + "\n", + " except Exception as e:\n", + " # Captura de cualquier excepción inesperada\n", + " print(f\"\\nAn unexpected error occurred: {e}\")\n", + " else:\n", + " # Solo se ejecuta si no hubo excepciones en el try\n", + " print()\n", + " print_order_statistics(order_stats)\n", + " print_update_inventory(inventory)\n", + " finally:\n", + " # Siempre se ejecuta\n", + " print(\"\\nProgram finished. Thank you for using the system.\")\n", + "\n", + "\n", + "if __name__ == \"__main__\":\n", + " main()\n", + "\n", + "\n" ] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "Python 3", "language": "python", "name": "python3" }, @@ -66,7 +245,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.12.9" } }, "nbformat": 4,