From 2b90294c71972c436aa7f9b75651262e39c28fa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20del=20Roc=C3=ADo=20Romo=20Garc=C3=ADa?= Date: Tue, 18 Feb 2025 20:58:40 +0100 Subject: [PATCH 1/2] Commit --- lab-python-error-handling.ipynb | 114 ++++++++++++++++++++++++++------ 1 file changed, 94 insertions(+), 20 deletions(-) diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index 3e50ef8..86b9962 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -10,43 +10,117 @@ }, { "cell_type": "markdown", - "id": "6f8e446f-16b4-4e21-92e7-9d3d1eb551b6", + "id": "bc99b386-7508-47a0-bcdb-d969deaf6c8b", "metadata": {}, "source": [ - "Objective: Practice how to identify, handle and recover from potential errors in Python code using try-except blocks." - ] - }, - { - "cell_type": "markdown", - "id": "e253e768-aed8-4791-a800-87add1204afa", - "metadata": {}, - "source": [ - "## Challenge \n", + "## Exercise: Error Handling for Managing Customer Orders\n", + "\n", + "The implementation of your code for managing customer orders assumes that the user will always enter a valid input. \n", + "\n", + "For example, we could modify the `initialize_inventory` function to include error handling.\n", + " - If the user enters an invalid quantity (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter the quantity for that product.\n", + " - Use a try-except block to handle the error and continue prompting the user until a valid quantity is entered.\n", + "\n", + "```python\n", + "# Step 1: Define the function for initializing the inventory with error handling\n", + "def initialize_inventory(products):\n", + " inventory = {}\n", + " for product in products:\n", + " valid_quantity = False\n", + " while not valid_quantity:\n", + " try:\n", + " quantity = int(input(f\"Enter the quantity of {product}s available: \"))\n", + " if quantity < 0:\n", + " raise ValueError(\"Invalid quantity! Please enter a non-negative value.\")\n", + " valid_quantity = True\n", + " except ValueError as error:\n", + " print(f\"Error: {error}\")\n", + " inventory[product] = quantity\n", + " return inventory\n", + "\n", + "# Or, in another way:\n", + "\n", + "def initialize_inventory(products):\n", + " inventory = {}\n", + " for product in products:\n", + " valid_input = False\n", + " while not valid_input:\n", + " try:\n", + " quantity = int(input(f\"Enter the quantity of {product}s available: \"))\n", + " if quantity >= 0:\n", + " inventory[product] = quantity\n", + " valid_input = True\n", + " else:\n", + " print(\"Quantity cannot be negative. Please enter a valid quantity.\")\n", + " except ValueError:\n", + " print(\"Invalid input. Please enter a valid quantity.\")\n", + " return inventory\n", + "```\n", "\n", - "Paste here your lab *functions* solutions. Apply error handling techniques to each function using try-except blocks. " + "Let's enhance your code by implementing error handling to handle invalid inputs.\n", + "\n", + "Follow the steps below to complete the exercise:\n", + "\n", + "2. Modify the `calculate_total_price` function to include error handling.\n", + " - If the user enters an invalid price (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter the price for that product.\n", + " - Use a try-except block to handle the error and continue prompting the user until a valid price is entered.\n", + "\n", + "3. Modify the `get_customer_orders` function to include error handling.\n", + " - If the user enters an invalid number of orders (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter the number of orders.\n", + " - If the user enters an invalid product name (e.g., a product name that is not in the inventory), or that doesn't have stock available, display an error message and ask them to re-enter the product name. *Hint: you will need to pass inventory as a parameter*\n", + " - Use a try-except block to handle the error and continue prompting the user until a valid product name is entered.\n", + "\n", + "4. Test your code by running the program and deliberately entering invalid quantities and product names. Make sure the error handling mechanism works as expected.\n" ] }, { - "cell_type": "markdown", - "id": "9180ff86-c3fe-4152-a609-081a287fa1af", + "cell_type": "code", + "execution_count": null, + "id": "f8dbbe5a", "metadata": {}, + "outputs": [], "source": [ - "The try-except block in Python is designed to handle exceptions and provide a fallback mechanism when code encounters errors. By enclosing the code that could potentially throw errors in a try block, followed by specific or general exception handling in the except block, we can gracefully recover from errors and continue program execution.\n", + "def precio_tot():\n", + " while True:\n", + " input_precio = float(input(\"Por favor ingresa el precio del articulo: \"))\n", + " try:\n", + " price = (input_precio) \n", + " if price < 0:\n", + " raise ValueError(\"El valor debe ser positivo \")\n", + " return price \n", + " except ValueError as e:\n", + " print(f\"Has puesto un valor imposible {e}. Por favor mete uno valido \")\n", "\n", - "However, there may be cases where an input may not produce an immediate error, but still needs to be addressed. In such situations, it can be useful to explicitly raise an error using the \"raise\" keyword, either to draw attention to the issue or handle it elsewhere in the program.\n", - "\n", - "Modify the code to handle possible errors in Python, it is recommended to use `try-except-else-finally` blocks, incorporate the `raise` keyword where necessary, and print meaningful error messages to alert users of any issues that may occur during program execution.\n", - "\n" + "product_price = precio_tot()\n", + "print(f\"El precio que has puesto son {product_price:.2f} €\")" ] }, { "cell_type": "code", "execution_count": null, - "id": "cc2c441d-9dcf-4817-b097-cf6cbe440846", + "id": "ff5a572f", "metadata": {}, "outputs": [], "source": [ - "# your code goes here" + "def get_customers_orders():\n", + " customers_orders = set()\n", + " while True:\n", + " try:\n", + " product = input(\"Por favor escribe lo que quieras comprar, si deseas cancelar la compra escribe salir\").strip()\n", + " if product.lower() == \"salir\":\n", + " print(\"Muchas gracias por tu compra\")\n", + " break\n", + " except ValueError as e:\n", + " if product > 1:\n", + " customers_orders.add(product) \n", + " input(\"¿Quieres añadir algo mas?, si quieres salir escribe salir\")\n", + " elif product < 0: \n", + " raise \"Estas intentando eliminar el articulo\"\n", + " else:\n", + " print(f\"No tenemos {product} en el inventario, por favor intentalo de nuevo\")\n", + " return customers_orders\n", + "\n", + "pedidos = get_customers_orders()\n" ] } ], From 5378a7fa51a4913d23b370af07160f627879038f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20del=20Roc=C3=ADo=20Romo=20Garc=C3=ADa?= Date: Tue, 18 Feb 2025 21:14:45 +0100 Subject: [PATCH 2/2] Commit --- lab-python-error-handling.ipynb | 62 +++++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 11 deletions(-) diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index 86b9962..d927669 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -75,10 +75,43 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "f8dbbe5a", + "execution_count": 3, + "id": "33ee82bb", "metadata": {}, "outputs": [], + "source": [ + "\n", + "def initialize_inventory(products):\n", + " inventory = {}\n", + " for product in products:\n", + " valid_input = False\n", + " while not valid_input:\n", + " try:\n", + " quantity = int(input(f\"Enter the quantity of {product}s available: \"))\n", + " if quantity >= 0:\n", + " inventory[product] = quantity\n", + " valid_input = True\n", + " else:\n", + " print(\"Quantity cannot be negative. Please enter a valid quantity.\")\n", + " except ValueError:\n", + " print(\"Invalid input. Please enter a valid quantity.\")\n", + " return inventory" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "f8dbbe5a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "El precio que has puesto son 5.00 €\n" + ] + } + ], "source": [ "def precio_tot():\n", " while True:\n", @@ -100,7 +133,15 @@ "execution_count": null, "id": "ff5a572f", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Muchas gracias por tu compra\n" + ] + } + ], "source": [ "def get_customers_orders():\n", " customers_orders = set()\n", @@ -110,14 +151,13 @@ " if product.lower() == \"salir\":\n", " print(\"Muchas gracias por tu compra\")\n", " break\n", - " except ValueError as e:\n", - " if product > 1:\n", + " elif product not in inventory[product] <= 0:\n", + " raise ValueError(f\"No tenemos {product} en el inventario, por favor inténtalo de nuevo\")\n", + " else:\n", " customers_orders.add(product) \n", " input(\"¿Quieres añadir algo mas?, si quieres salir escribe salir\")\n", - " elif product < 0: \n", - " raise \"Estas intentando eliminar el articulo\"\n", - " else:\n", - " print(f\"No tenemos {product} en el inventario, por favor intentalo de nuevo\")\n", + " except ValueError as e:\n", + " print(e)\n", " return customers_orders\n", "\n", "pedidos = get_customers_orders()\n" @@ -126,7 +166,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "Python 3", "language": "python", "name": "python3" }, @@ -140,7 +180,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.12.5" } }, "nbformat": 4,