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
280 changes: 280 additions & 0 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,280 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e",
"metadata": {},
"source": [
"# Lab | Error Handling"
]
},
{
"cell_type": "markdown",
"id": "bc99b386-7508-47a0-bcdb-d969deaf6c8b",
"metadata": {},
"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",
"execution_count": 3,
"id": "1ba4db8c",
"metadata": {},
"outputs": [],
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "0591e99b",
"metadata": {},
"outputs": [],
"source": [
"def initialize_inventory(products):\n",
" inventory = {}\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" quantity = int(input(f\"Enter the quantity of {product}s available: \"))\n",
" if quantity >= 0:\n",
" inventory[product] = quantity\n",
" break\n",
" else:\n",
" print(\"Quantity cannot be negative. Please enter a non-negative number.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid number for the quantity.\")\n",
" formatted_items = [f\"Enter the quantity of {product}s available: {quantity}\" for product, quantity in inventory.items()]\n",
" for item in formatted_items:\n",
" print(item)\n",
" return inventory"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "1060e123",
"metadata": {},
"outputs": [],
"source": [
"def get_customer_orders(inventory):\n",
" num_orders = []\n",
" while True:\n",
" try:\n",
" num_orders_input = int(input(\"Enter the number of products you wish to order: \"))\n",
" if num_orders_input >= 0:\n",
" num_orders = num_orders_input\n",
" break\n",
" else:\n",
" print(\"Please enter a valide number.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a number for the number of products.\")\n",
" print(f\"Enter the number of customer orders: {num_orders}\")\n",
" orders = set()\n",
" while len(orders) < num_orders:\n",
" try:\n",
" order = input(f\"Enter product name {len(orders)+1}: \")\n",
" if order not in inventory:\n",
" print(\"The product is not available in the inventory.\")\n",
" elif inventory[order] <= 0:\n",
" print(\"The product is out of stock.\")\n",
" else:\n",
" orders.add(order)\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid product name.\")\n",
" formatted_orders = [f\"Enter the name of a product that a customer wants to order: {order}\" for order in sorted(orders)]\n",
" for order in formatted_orders:\n",
" print(order)\n",
" return orders"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "c185d4ec",
"metadata": {},
"outputs": [],
"source": [
"def calculate_order_total_price(customer_orders):\n",
" prices = []\n",
"\n",
" while len(prices) < len(customer_orders):\n",
" try:\n",
" for order in customer_orders:\n",
" if len(prices) < len(customer_orders):\n",
" price = float(input(f\"Enter the price of {order}: \"))\n",
" if price <= 0:\n",
" print(\"Invalid input. Please enter a valid number price.\")\n",
" else:\n",
" prices.append(price)\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid number price.\")\n",
"\n",
" for order, price in zip(customer_orders, prices):\n",
" print(f\"The price of {order}: {price}\")\n",
"\n",
" total_price = sum(prices)\n",
" print(f\"Total price: {total_price:.2f}\")\n",
" \n",
" return total_price"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "6f4c99a7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the quantity of t-shirts available: 10\n",
"Enter the quantity of mugs available: 10\n",
"Enter the quantity of hats available: 10\n",
"Enter the quantity of books available: 0\n",
"Enter the quantity of keychains available: 2\n"
]
}
],
"source": [
"inventory = initialize_inventory(products)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "a26e77eb",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input. Please enter a number for the number of products.\n",
"Please enter a valide number.\n",
"Enter the number of customer orders: 2\n",
"The product is out of stock.\n",
"Enter the name of a product that a customer wants to order: hat\n",
"Enter the name of a product that a customer wants to order: mug\n"
]
}
],
"source": [
"customer_orders = get_customer_orders(inventory)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "b80afb3c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input. Please enter a valid number price.\n",
"Invalid input. Please enter a valid number price.\n",
"The price of mug: 10.28\n",
"The price of hat: 25.54\n",
"Total price: 35.82\n"
]
},
{
"data": {
"text/plain": [
"35.82"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"calculate_order_total_price(customer_orders)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"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.13.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}