Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 132 additions & 18 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -10,49 +10,163 @@
},
{
"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."
"## 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",
"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": "e253e768-aed8-4791-a800-87add1204afa",
"cell_type": "code",
"execution_count": 3,
"id": "33ee82bb",
"metadata": {},
"outputs": [],
"source": [
"## Challenge \n",
"\n",
"Paste here your lab *functions* solutions. Apply error handling techniques to each function using try-except blocks. "
"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": "markdown",
"id": "9180ff86-c3fe-4152-a609-081a287fa1af",
"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": [
"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",
"\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",
"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",
"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": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Muchas gracias por tu compra\n"
]
}
],
"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",
" 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",
" except ValueError as e:\n",
" print(e)\n",
" return customers_orders\n",
"\n",
"pedidos = get_customers_orders()\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
Expand All @@ -66,7 +180,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.12.5"
}
},
"nbformat": 4,
Expand Down