Skip to content

Solved lab - Error handling #453

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
267 changes: 267 additions & 0 deletions lab-python-error-handling-solved.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
{
"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": null,
"id": "7c9c7dbf",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# 1. Initialize inventory with error handling\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"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3a9497a8",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# 2. Get customer orders with error handling\n",
"def get_customer_orders(inventory):\n",
" customer_orders = set()\n",
" while True:\n",
" try:\n",
" num_orders = int(input(\"Enter the number of customer orders: \"))\n",
" if num_orders < 0:\n",
" print(\"Number of orders cannot be negative. Try again.\")\n",
" continue\n",
" break\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid number.\")\n",
"\n",
" while len(customer_orders) < num_orders:\n",
" order = input(\"Enter the name of a product that a customer wants to order: \").strip()\n",
" if order not in inventory:\n",
" print(\"Invalid product. Product not found in inventory.\")\n",
" elif inventory[order] == 0:\n",
" print(\"This product is out of stock.\")\n",
" else:\n",
" customer_orders.add(order)\n",
" return customer_orders\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fd08928b",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# 3. Update inventory and remove zero quantity products using comprehension\n",
"def update_inventory(customer_orders, inventory):\n",
" for order in customer_orders:\n",
" if order in inventory and inventory[order] > 0:\n",
" inventory[order] -= 1\n",
" inventory = {product: qty for product, qty in inventory.items() if qty > 0}\n",
" return inventory\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "89ae0ef1",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# 4. Calculate order statistics\n",
"def calculate_order_statistics(customer_orders, products):\n",
" total_products_ordered = len(customer_orders)\n",
" unique_products_ordered = len([p for p in customer_orders if p in products])\n",
" percentage_unique = (unique_products_ordered / len(products)) * 100 if products else 0\n",
" return total_products_ordered, percentage_unique\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6ca81642",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# 5. Print order statistics\n",
"def print_order_statistics(order_statistics):\n",
" total, percentage = order_statistics\n",
" print(\"\\nOrder Statistics:\")\n",
" print(f\"Total Products Ordered: {total}\")\n",
" print(f\"Percentage of Unique Products Ordered: {percentage:.1f}\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3ac18960",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# 6. Print updated inventory\n",
"def print_updated_inventory(inventory):\n",
" print(\"\\nUpdated Inventory:\")\n",
" for product, qty in inventory.items():\n",
" print(f\"{product}: {qty}\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c3bea7b2",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# 7. Calculate total price with error handling\n",
"def calculate_total_price(customer_orders):\n",
" prices = {}\n",
" for product in customer_orders:\n",
" valid_price = False\n",
" while not valid_price:\n",
" try:\n",
" price = float(input(f\"Enter the price of {product}: \"))\n",
" if price < 0:\n",
" print(\"Price cannot be negative. Try again.\")\n",
" else:\n",
" prices[product] = price\n",
" valid_price = True\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid price.\")\n",
" total_price = sum(prices.values())\n",
" return total_price\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "90438afe",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# 8. Main flow\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"inventory = initialize_inventory(products)\n",
"customer_orders = get_customer_orders(inventory)\n",
"inventory = update_inventory(customer_orders, inventory)\n",
"order_stats = calculate_order_statistics(customer_orders, products)\n",
"print_order_statistics(order_stats)\n",
"print_updated_inventory(inventory)\n",
"total_price = calculate_total_price(customer_orders)\n",
"print(f\"\\nTotal Price: {total_price}\")\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:base] *",
"language": "python",
"name": "conda-base-py"
},
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}