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
318 changes: 318 additions & 0 deletions lab_python_error_handling.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,318 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/letter-b/lab-python-error-handling/blob/main/lab_python_error_handling.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e",
"metadata": {
"id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e"
},
"source": [
"# Lab | Error Handling"
]
},
{
"cell_type": "markdown",
"id": "bc99b386-7508-47a0-bcdb-d969deaf6c8b",
"metadata": {
"id": "bc99b386-7508-47a0-bcdb-d969deaf6c8b"
},
"source": [
"## 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": "code",
"source": [
"# Modify the calculate_total_price function to include error handling.\n",
"def calculate_total_price(customer_orders):\n",
" price = {}\n",
" for product in customer_orders:\n",
" valid_price = False\n",
" while not valid_price:\n",
" try:\n",
" price_product = float(input(f\"Enter the price of {product}: \"))\n",
" if price_product >= 0:\n",
" price[product] = price_product\n",
" valid_price = True\n",
" else:\n",
" print(\"Price needs to be a positive number. Please enter a valid price.\")\n",
" except ValueError:\n",
" print(\"Price needs to be a positive number. Please enter a valid price.\")\n",
"\n",
" return price"
],
"metadata": {
"id": "wWU4uRX_Ngin"
},
"id": "wWU4uRX_Ngin",
"execution_count": 8,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def get_customer_orders(inventory):\n",
" customer_orders = {}\n",
" valid_num_orders = False\n",
" while not valid_num_orders:\n",
" try:\n",
" num_orders = int(input(\"Enter the total number of customer orders you want to process: \"))\n",
" if num_orders < 0:\n",
" raise ValueError(\"Number of orders cannot be negative. Please enter a valid number.\")\n",
" valid_num_orders = True\n",
" except ValueError as e:\n",
" print(f\"Error: {e}. Please enter a valid integer for the number of orders.\")\n",
"\n",
" for i in range(num_orders):\n",
" valid_product = False\n",
" while not valid_product:\n",
" try:\n",
" product_name = input(f\"Enter the product name for order {i+1}: \").strip().lower()\n",
" if product_name not in inventory:\n",
" raise ValueError(f\"Product '{product_name}' not found in inventory. Please enter a valid product name.\")\n",
"\n",
" quantity = int(input(f\"Enter the quantity for {product_name}: \"))\n",
" if quantity <= 0:\n",
" raise ValueError(\"Quantity must be a positive number.\")\n",
" if quantity > inventory[product_name]:\n",
" raise ValueError(f\"Insufficient stock for {product_name}. Available: {inventory[product_name]}\")\n",
"\n",
" customer_orders[product_name] = customer_orders.get(product_name, 0) + quantity\n",
" valid_product = True\n",
" except ValueError as e:\n",
" print(f\"Error: {e}. Please try again.\")\n",
" return customer_orders"
],
"metadata": {
"id": "Q5Pp1S7RP_Tk"
},
"id": "Q5Pp1S7RP_Tk",
"execution_count": 11,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#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",
"inventory = {\"shoes\": 12, \"shirts\": 20, \"pants\": 13, \"hats\": 24, \"t-shirts\": 14}\n",
"customer_orders = get_customer_orders(inventory)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "dOm0Y8itSMk6",
"outputId": "51d9dfd1-e77e-4c68-a6a4-979bd5f9b817"
},
"id": "dOm0Y8itSMk6",
"execution_count": 19,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the total number of customer orders you want to process: 6\n",
"Enter the product name for order 1: shows\n",
"Error: Product 'shows' not found in inventory. Please enter a valid product name.. Please try again.\n",
"Enter the product name for order 1: shoes\n",
"Enter the quantity for shoes: belts\n",
"Error: invalid literal for int() with base 10: 'belts'. Please try again.\n",
"Enter the product name for order 1: shoes\n",
"Enter the quantity for shoes: 2\n",
"Enter the product name for order 2: hats\n",
"Enter the quantity for hats: 1\n",
"Enter the product name for order 3: t-shirts\n",
"Enter the quantity for t-shirts: 3\n",
"Enter the product name for order 4: pants\n",
"Enter the quantity for pants: test\n",
"Error: invalid literal for int() with base 10: 'test'. Please try again.\n",
"Enter the product name for order 4: pants\n",
"Enter the quantity for pants: 2\n",
"Enter the product name for order 5: shirts\n",
"Enter the quantity for shirts: 2\n",
"Enter the product name for order 6: shoes\n",
"Enter the quantity for shoes: 1\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"calculate_total_price(customer_orders)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "1jUzf9yfTrYD",
"outputId": "fc25590a-8120-451a-a693-c819f8f21617"
},
"id": "1jUzf9yfTrYD",
"execution_count": 20,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the price of shoes: 24.99\n",
"Enter the price of hats: 12.99\n",
"Enter the price of t-shirts: 14.99\n",
"Enter the price of pants: 18.99\n",
"Enter the price of shirts: 23.99\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"{'shoes': 24.99,\n",
" 'hats': 12.99,\n",
" 't-shirts': 14.99,\n",
" 'pants': 18.99,\n",
" 'shirts': 23.99}"
]
},
"metadata": {},
"execution_count": 20
}
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "403b73da",
"outputId": "1a90d020-3b0e-42c4-d0a2-64f44d02373e"
},
"source": [
"def calculate_order_grand_total(customer_orders, unit_prices):\n",
" grand_total = 0\n",
" for product, quantity in customer_orders.items():\n",
" if product in unit_prices:\n",
" grand_total += quantity * unit_prices[product]\n",
" else:\n",
" print(f\"Warning: Price not found for {product}. Skipping this product in total calculation.\")\n",
" return grand_total\n",
"\n",
"# Assuming 'customer_orders' and 'prices' (from calculate_total_price) are available\n",
"# We'll use the variable 'prices' as the output of calculate_total_price was stored there\n",
"prices = calculate_total_price(customer_orders) # Re-run to ensure 'prices' is populated if not already\n",
"\n",
"final_total_cost = calculate_order_grand_total(customer_orders, prices)\n",
"print(f\"\\nGrand Total for the customer order: ${final_total_cost:.2f}\")"
],
"id": "403b73da",
"execution_count": 21,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Enter the price of shoes: 24.99\n",
"Enter the price of hats: 12.99\n",
"Enter the price of t-shirts: 16.99\n",
"Enter the price of pants: 18.99\n",
"Enter the price of shirts: 21.99\n",
"\n",
"Grand Total for the customer order: $220.89\n"
]
}
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
},
"colab": {
"provenance": [],
"include_colab_link": true
}
},
"nbformat": 4,
"nbformat_minor": 5
}