diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index 3e50ef8..9e664ff 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -41,18 +41,373 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "id": "cc2c441d-9dcf-4817-b097-cf6cbe440846", "metadata": {}, "outputs": [], "source": [ - "# your code goes here" + "# your code goes here\n", + "# Creamos una lista de productos\n", + "products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "63c2f35b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ERROR: Quantity must be a non-negative integer.\n", + "Please, try again.\n", + "ERROR: Quantity must be a non-negative integer.\n", + "Please, try again.\n", + "t-shirt added succesfully.\n", + "mug added succesfully.\n", + "hat added succesfully.\n", + "book added succesfully.\n", + "keychain added succesfully.\n", + "Initial inventory: {'t-shirt': 2, 'mug': 3, 'hat': 9, 'book': 5, 'keychain': 6}\n" + ] + } + ], + "source": [ + "# Definimos una funcion\n", + "def initialize_inventory(products):\n", + " inventory = {}\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " quantity = input(f\"Enter the quantity of each {product} in the inventory: \")\n", + "\n", + " # Validacion manual: raise si no es entero no negativo\n", + " if not quantity.isdigit():\n", + " raise ValueError(\"Quantity must be a non-negative integer.\")\n", + " \n", + " quantity_int = int(quantity)\n", + " \n", + " if quantity_int < 0:\n", + " raise ValueError(\"Quantity cannot be negative.\")\n", + " \n", + " except ValueError as ve:\n", + " # Mensajes de error para el usuario\n", + " print(f\"ERROR: {ve}\")\n", + " print(\"Please, try again.\")\n", + "\n", + " else:\n", + " # Si no hay errores, guardamos el valor y salimos del bucle\n", + " inventory[product] = quantity_int\n", + " print(f\"{product} added succesfully.\")\n", + " break\n", + "\n", + " finally:\n", + " # Este bloque siempre se ejecuta\n", + " pass\n", + "\n", + " return inventory\n", + "inventory = initialize_inventory(products)\n", + "print(f\"Initial inventory: {inventory}\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "9fff47f7", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ERROR Product not found. Enter a valid product name\n", + "Please, try again\n", + "t-shirt added to order\n", + "mug added to order\n", + "Customer orders: {'t-shirt', 'mug'}\n" + ] + } + ], + "source": [ + "# Definimos otra funcion para pedir al usuario productos\n", + "def get_customer_order():\n", + " customer_orders = set()\n", + " while True:\n", + " try:\n", + " order = input(\"Enter the product name to order (or type 'done' to finish):\").strip().lower()\n", + "\n", + " # Validaciones basicas\n", + " if order == \"\":\n", + " raise ValueError (\"Input cannot be empty. Please enter a product name or 'done'.\")\n", + " \n", + " if order.lower() == 'done':\n", + " break\n", + "\n", + " # Validar si el producto aparece en la lista\n", + " product_list_lower = [p.lower() for p in products]\n", + " if order not in product_list_lower:\n", + " raise ValueError(\"Product not found. Enter a valid product name\")\n", + " \n", + " except ValueError as ve:\n", + " print(f\"ERROR {ve}\")\n", + " print(\"Please, try again\")\n", + "\n", + " except Exception as e:\n", + " print(f\"Unexpected error: {e}\")\n", + " print(\"Please, try again\")\n", + "\n", + " else:\n", + " # Encontrar el producto original\n", + " for product in products:\n", + " if product.lower() == order:\n", + " customer_orders.add(product)\n", + " print(f\"{product} added to order\")\n", + " break\n", + "\n", + " finally:\n", + " pass # Siempre se ejecuta\n", + "\n", + " return customer_orders\n", + "\n", + "customer_orders = get_customer_order()\n", + "print(f\"Customer orders: {customer_orders}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "095f1d04", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "t-shirt updated successfully. Reaming: 1\n", + "mug updated successfully. Reaming: 2\n", + "Update inventory: {'t-shirt': 1, 'mug': 2, 'hat': 9, 'book': 5, 'keychain': 6}\n" + ] + } + ], + "source": [ + "# Definimos otra funcion para actualizar inventario\n", + "def update_inventory(inventory, customer_orders):\n", + " for order in customer_orders:\n", + " try:\n", + " # Validar que el producto existe\n", + " if order not in inventory:\n", + " raise KeyError(f\"Product '{order}' does not exist in the inventory.\")\n", + " \n", + " # Validar que la cantidad no sea negativa\n", + " if inventory[order] > 0:\n", + " inventory[order] -= 1\n", + " print(f\"{order} updated successfully. Reaming: {inventory[order]}\")\n", + " else:\n", + " print(f\"The {order} is out of stock\")\n", + "\n", + " except KeyError as ke:\n", + " print(f\"ERROR: {ke}\")\n", + "\n", + " except ValueError as ve:\n", + " print(f\"ERROR: {ve}\")\n", + " \n", + " except Exception as e:\n", + " print(f\"Unexpected error: {e}\")\n", + " \n", + " else:\n", + " # Se ejecuta solo si no hubo errores\n", + " pass\n", + " finally:\n", + " # Se ejecuta siempre\n", + " pass\n", + "\n", + " return inventory\n", + "print(f\"Update inventory: {update_inventory(inventory, customer_orders)}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "d187c6b9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Order Statitics: \n", + "Total number of products ordered: 2 \n", + "Percentage of total products ordered: 40.0%\n" + ] + } + ], + "source": [ + "# Definimos otra función para imprimir las estadisticas del pedido\n", + "def calculate_order_statistics(products, customer_orders):\n", + " try:\n", + " # Validar que las listas no estén vacias\n", + " if len(products) == 0:\n", + " raise ValueError(\"Product list cannot be empty:\")\n", + " if not isinstance(customer_orders, (set, list, tuple)):\n", + " raise TypeError(\"Customer orders must be a set, list or tuple.\")\n", + " \n", + " total_products_ordered = len(customer_orders)\n", + " # Calcular porcentaje\n", + " percentage_ordered = (total_products_ordered / len(products)) * 100\n", + "\n", + " except (ValueError, TypeError) as ve:\n", + " print(f\"ERROR: {ve}\")\n", + " return 0, 0 # Devolvemos valores seguros\n", + " \n", + " except (Exception) as e:\n", + " print(f\"Unexpected erro: {e}\")\n", + " return 0, 0\n", + " else:\n", + " return total_products_ordered, percentage_ordered\n", + " \n", + " finally:\n", + " pass\n", + "\n", + "def print_order_statistics(order_statistics):\n", + " try:\n", + " total_products_ordered, percentage_ordered = order_statistics\n", + "\n", + " # Validar tipos\n", + " if not isinstance(total_products_ordered, int):\n", + " raise TypeError(\"Total products ordered must be an integer.\")\n", + " \n", + " if not isinstance(percentage_ordered, (int, float)):\n", + " raise TypeError(\"Percentage ordered must be a numeric value\")\n", + " \n", + " print(\"\\nOrder Statitics: \")\n", + " print(f\"Total number of products ordered: {total_products_ordered} \")\n", + " print(f\"Percentage of total products ordered: {percentage_ordered:}%\")\n", + " \n", + " except (ValueError, TypeError) as ve:\n", + " print(f\"ERROR: {ve}\")\n", + " \n", + " except (Exception) as e:\n", + " print(f\"Unexpected error: {e}\")\n", + "\n", + " finally:\n", + " pass\n", + "\n", + "order_statistics = calculate_order_statistics(products, customer_orders)\n", + "print_order_statistics(order_statistics)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "e783c911", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Updated Inventory: \n", + "t-shirt: 1\n", + "mug: 2\n", + "hat: 9\n", + "book: 5\n", + "keychain: 6\n" + ] + } + ], + "source": [ + "# Imprimos el inventario actualizado\n", + "def print_updated_inventory(inventory):\n", + " try:\n", + " # Validar que invetory sea un diccionario\n", + " if not isinstance(inventory, dict):\n", + " raise TypeError(\"Inventory must be a dictionary.\")\n", + " # Validar que no este vacio\n", + " if len(inventory) == 0:\n", + " raise ValueError(\"Inventory is empty. Nothing to print.\")\n", + " \n", + " except (TypeError, ValueError) as ve:\n", + " print(f\"ERROR: {ve}\")\n", + "\n", + " except Exception as e:\n", + " print(f\"Unexpected error: {e}\")\n", + "\n", + " else:\n", + " print(\"\\nUpdated Inventory: \")\n", + " for product, quantity in inventory.items():\n", + " print(f\"{product}: {quantity}\")\n", + " \n", + " finally:\n", + " pass\n", + "\n", + "print_updated_inventory(inventory)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "292c423f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "t-shirt added succesfully.\n", + "mug added succesfully.\n", + "hat added succesfully.\n", + "book added succesfully.\n", + "keychain added succesfully.\n", + "ERROR Product not found. Enter a valid product name\n", + "Please, try again\n", + "t-shirt added to order\n", + "mug added to order\n", + "t-shirt updated successfully. Reaming: 8\n", + "mug updated successfully. Reaming: 7\n", + "\n", + "Order Statitics: \n", + "Total number of products ordered: 2 \n", + "Percentage of total products ordered: 40.0%\n", + "\n", + "Updated Inventory: \n", + "t-shirt: 8\n", + "mug: 7\n", + "hat: 7\n", + "book: 6\n", + "keychain: 5\n", + "\n", + "Program finished. Thank you!\n" + ] + } + ], + "source": [ + "def main():\n", + " try:\n", + " inventory = initialize_inventory(products)\n", + " customer_orders = get_customer_order()\n", + " inventory = update_inventory(inventory, customer_orders)\n", + "\n", + " order_statistics = calculate_order_statistics(products, customer_orders)\n", + " print_order_statistics(order_statistics)\n", + "\n", + " print_updated_inventory(inventory)\n", + "\n", + " except Exception as e:\n", + " print(f\"Unexpected error in main program: {e}\")\n", + "\n", + " finally:\n", + " print(\"\\nProgram finished. Thank you!\")\n", + "main()" ] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "Python 3", "language": "python", "name": "python3" }, @@ -66,7 +421,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.12.9" } }, "nbformat": 4,