Skip to content
Open
Show file tree
Hide file tree
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
391 changes: 391 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,391 @@
{
"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": 68,
"id": "1cce3eb4-8c8d-4e4d-a6ae-1938d735facf",
"metadata": {},
"outputs": [],
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]"
]
},
{
"cell_type": "code",
"execution_count": 69,
"id": "ac015339-ffbc-43fb-96ad-bc68c6b143ae",
"metadata": {},
"outputs": [],
"source": [
"# Step 1: Define the function for initializing the inventory with error handling\n",
"\n",
"def initialize_inventory(products):\n",
" inventory = {}\n",
" \n",
" for product in products:\n",
" valid_quantity = False\n",
" \n",
" while not valid_quantity:\n",
" try:\n",
" quantity = int(input(f\"Enter the quantity of {product}s available: \"))\n",
" \n",
" if quantity < 0:\n",
" raise ValueError(\"Invalid quantity! Please enter a non-negative value.\")\n",
" \n",
" valid_quantity = True\n",
" \n",
" except ValueError as error:\n",
" print(f\"Error: {error}\")\n",
" \n",
" inventory[product] = quantity\n",
" return inventory"
]
},
{
"cell_type": "code",
"execution_count": 70,
"id": "d8c7db11-aee9-48be-8f27-70ca51b98398",
"metadata": {},
"outputs": [],
"source": [
"\n",
"def get_valid_orders():\n",
" while True:\n",
" try:\n",
" valid_orders = int(input(\"Enter the number of customer orders: \"))\n",
" \n",
" if valid_orders < 0:\n",
" print(\"Error: Order Number cannot be negative. Try Again!!\")\n",
" continue\n",
" return valid_orders\n",
" except ValueError:\n",
" print(\"Error: Please enter valid number of orders\")"
]
},
{
"cell_type": "code",
"execution_count": 71,
"id": "796eab51-237a-4b69-b06b-ac146e1ff0f5",
"metadata": {},
"outputs": [],
"source": [
"def get_valid_product(inventory):\n",
" while True:\n",
" product = input(\"Enter the product name that a customer wants to order: \").strip().lower()\n",
"\n",
" if product not in products:\n",
" print(\"Invalid Product. Choose from: \", products)\n",
" continue\n",
"\n",
" if inventory.get(product, 0) <= 0:\n",
" print(f\"Error: '{product}' is not in stock. Choose another product: \")\n",
" continue\n",
"\n",
" return product"
]
},
{
"cell_type": "code",
"execution_count": 72,
"id": "5a2de987-fea9-47d5-a0a7-d8698d101170",
"metadata": {},
"outputs": [],
"source": [
"def get_customer_orders(inventory):\n",
" num_orders = get_valid_orders()\n",
"\n",
" if num_orders == 0:\n",
" return set()\n",
"\n",
" orders = [get_valid_product(inventory) for _ in range(num_orders)]\n",
"\n",
" customer_orders = set(orders)\n",
" return customer_orders"
]
},
{
"cell_type": "code",
"execution_count": 73,
"id": "65212efb-03d0-43e0-b1c6-504f79c8970f",
"metadata": {},
"outputs": [],
"source": [
"def calculate_order_statistics(customer_orders, products):\n",
" total_products_ordered = len(customer_orders)\n",
"\n",
" if len(products) == 0:\n",
" percentage_ordered = 0\n",
" else:\n",
" percentage_ordered = (total_products_ordered / len(products)) * 100\n",
"\n",
" return total_products_ordered, percentage_ordered"
]
},
{
"cell_type": "code",
"execution_count": 74,
"id": "09c81448-cff1-4e4d-8fb2-fd6dfa9601d2",
"metadata": {},
"outputs": [],
"source": [
"def update_inventory(customer_orders, inventory):\n",
" \n",
" updated_inventory = {\n",
" product: quantity - (1 if product in customer_orders else 0)\n",
"\n",
" for product, quantity in inventory.items()\n",
"\n",
" if quantity - (1 if product in customer_orders else 0) > 0\n",
" }\n",
" return update_inventory"
]
},
{
"cell_type": "code",
"execution_count": 75,
"id": "bc161b13-c28e-4ea5-8c9e-d58953986c01",
"metadata": {},
"outputs": [],
"source": [
"def print_order_statistics(order_statistics):\n",
" \n",
" total_products_ordered, percentage_ordered = order_statistics\n",
" \n",
" print(\"\\nOrder statistics: \")\n",
" print(\"Total products ordered: \", total_products_ordered)\n",
" print(\"Percentage of products ordered: \", percentage_ordered)"
]
},
{
"cell_type": "code",
"execution_count": 80,
"id": "f49cb01d-de75-4864-99cb-b5fdf4419d69",
"metadata": {},
"outputs": [],
"source": [
"def print_updated_inventory(inventory):\n",
" print(\"\\nUpdated Inventory: \")\n",
" [print(f\"{product}: {quantity}\") for product, quantity in inventory.items()]"
]
},
{
"cell_type": "code",
"execution_count": 81,
"id": "0f551d37-8198-4490-930e-6faf24ba9179",
"metadata": {},
"outputs": [],
"source": [
"def get_valid_price(product):\n",
" \n",
" while True:\n",
" try:\n",
" price = float(input(f\"Enter the price of the {product}: \"))\n",
"\n",
" if price < 0:\n",
" print(\"Error: Price cannot be negative. Try again!!\")\n",
" continue\n",
" return price\n",
"\n",
" except ValueError:\n",
" print(\"Error: Please enter a valid numerical price: \")"
]
},
{
"cell_type": "code",
"execution_count": 82,
"id": "86d42222-f4b0-430e-9585-e60658a7f44d",
"metadata": {},
"outputs": [],
"source": [
"def calculate_total_price(customer_orders):\n",
" if not customer_orders:\n",
" return 0.0\n",
"\n",
" prices = {\n",
" product: get_valid_price(product)\n",
" for product in customer_orders\n",
" }\n",
" total_price = sum(prices.values())\n",
" return total_price"
]
},
{
"cell_type": "code",
"execution_count": 86,
"id": "c9b68a74-c134-48ff-8370-f9b6956a2897",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity of t-shirts available: 1\n",
"Enter the quantity of mugs available: 2\n",
"Enter the quantity of hats available: 3\n",
"Enter the quantity of books available: 4\n",
"Enter the quantity of keychains available: 5\n",
"Enter the number of customer orders: 1\n",
"Enter the product name that a customer wants to order: mug\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"Order statistics: \n",
"Total products ordered: 1\n",
"Percentage of products ordered: 20.0\n",
"dict_items([('t-shirt', 1), ('mug', 2), ('hat', 3), ('book', 4), ('keychain', 5)])\n",
"\n",
"Updated Inventory: \n",
"t-shirt: 1\n",
"mug: 2\n",
"hat: 3\n",
"book: 4\n",
"keychain: 5\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the price of the mug: 10\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Total Price: 10.0\n"
]
}
],
"source": [
"def main():\n",
" inventory = initialize_inventory(products)\n",
"\n",
" customer_orders = get_customer_orders(inventory)\n",
"\n",
" order_stats = calculate_order_statistics(customer_orders, products)\n",
" print()\n",
" print_order_statistics(order_stats)\n",
"\n",
" print(inventory.items())\n",
"\n",
" update_inventory(customer_orders, inventory)\n",
" \n",
" print_updated_inventory(inventory)\n",
"\n",
" total_price = calculate_total_price(customer_orders)\n",
" print(\"Total Price: \", total_price)\n",
"\n",
"if __name__ == \"__main__\":\n",
" main()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "274e92dd-ba10-437f-b881-b24cd7489a48",
"metadata": {},
"outputs": [],
"source": []
}
],
"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.13.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading