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
248 changes: 248 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
{
"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": "5820edf5-1ec5-4f0e-8e97-178268928853",
"metadata": {},
"outputs": [],
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"def initialize_inventory(products):\n",
" print(\"\\nINITIALIZING INVENTORY\")\n",
" inventory = {}\n",
" \n",
" for product in products:\n",
" while True:\n",
" try:\n",
" # 1. Error handling for invalid quantity (non-integer or negative)\n",
" quantity = int(input(f\"Enter quantity of {product}s available: \"))\n",
" if quantity < 0:\n",
" print(\"**Error:** Quantity must be a non-negative whole number. Please try again.\")\n",
" continue\n",
" inventory[product] = quantity\n",
" break\n",
" except ValueError:\n",
" print(\"**Error:** Invalid input. Please enter a whole number for the quantity.\")\n",
" \n",
" return inventory\n",
"\n",
"def get_customer_orders(inventory):\n",
" customer_orders = []\n",
" print(\"\\nSTARTING ORDER PROCESS\")\n",
"\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 must be non-negative. Try again.\")\n",
" continue\n",
" break\n",
" except ValueError:\n",
" print(\"Invalid input. Enter a whole number.\")\n",
"\n",
" print(\"--- Enter product names for order ---\")\n",
" \n",
" for i in range(num_orders):\n",
" while True:\n",
" product_name = input(f\"Enter the name of product {i+1} that a customer wants to order: \").strip()\n",
" if product_name in inventory:\n",
" customer_orders.append(product_name)\n",
" break\n",
" else:\n",
" print(f\"'{product_name}' not found. Try again.\")\n",
" \n",
" return customer_orders\n",
"\n",
"def calculate_total_price(customer_orders):\n",
" print(\"\\nCALCULATING TOTAL PRICE\")\n",
"\n",
" product_prices = {}\n",
" \n",
" # Get unique products to ask for price only once\n",
" unique_products_ordered = set(customer_orders)\n",
"\n",
" for product in unique_products_ordered:\n",
" while True:\n",
" try:\n",
" # 2. Error handling for invalid price (non-numeric or negative)\n",
" price_input = input(f\"Enter the price of {product}: \")\n",
" price = float(price_input)\n",
" if price < 0:\n",
" print(\"**Error:** Price must be non-negative. Please try again.\")\n",
" continue\n",
" product_prices[product] = price\n",
" break\n",
" except ValueError:\n",
" print(\"**Error:** Invalid input. Please enter a valid number (e.g., 19.99) for the price.\")\n",
" \n",
" total_price = sum(product_prices[product] for product in customer_orders)\n",
" \n",
" return total_price\n",
"\n",
"def update_inventory(customer_orders, inventory):\n",
" print(\"\\nUPDATING INVENTORY\")\n",
" \n",
" for product in customer_orders:\n",
" if product in inventory and inventory[product] > 0:\n",
" inventory[product] -= 1\n",
"\n",
" inventory = {\n",
" product: quantity\n",
" for product, quantity in inventory.items()\n",
" if quantity > 0\n",
" }\n",
" \n",
" return inventory\n",
"\n",
"def calculate_order_statistics(customer_orders, products):\n",
" print(\"\\nCALCULATING STATISTICS\")\n",
" \n",
" unique_products_ordered = set(customer_orders)\n",
" \n",
" total_products_ordered = len(customer_orders)\n",
" total_unique_products_available = len(products)\n",
" \n",
" if total_unique_products_available > 0:\n",
" percentage_ordered = (len(unique_products_ordered) / total_unique_products_available) * 100\n",
" else:\n",
" percentage_ordered = 0.0\n",
" \n",
" return total_products_ordered, percentage_ordered\n",
"\n",
"def print_order_statistics(total_products_ordered, percentage_ordered):\n",
" print(\"\\nORDER STATISTICS REPORT\")\n",
" print(f\"Total Products Ordered: {total_products_ordered}\")\n",
" print(f\"Percentage of Unique Products Ordered: {percentage_ordered:.2f}%\")\n",
"\n",
"def print_updated_inventory(inventory):\n",
" print(\"\\nUPDATED INVENTORY\")\n",
" \n",
" print(\"Product | Stock\")\n",
" print(\"----------------\")\n",
" for product, quantity in inventory.items():\n",
" print(f\"{product:<7} | {quantity}\")\n",
"\n",
"def main():\n",
" print(\"--- STARTING ORDER MANAGEMENT PROGRAM ---\")\n",
" \n",
" current_inventory = initialize_inventory(products)\n",
" \n",
" orders_list = get_customer_orders(current_inventory)\n",
" \n",
" total_price = calculate_total_price(orders_list)\n",
" \n",
" final_inventory = update_inventory(orders_list, current_inventory)\n",
" \n",
" total_ordered, percentage_stats = calculate_order_statistics(orders_list, products)\n",
" \n",
" print_order_statistics(total_ordered, percentage_stats)\n",
" \n",
" print_updated_inventory(final_inventory)\n",
"\n",
" # 5. Print the total price of the customer order (as requested in the screenshot)\n",
" print(f\"\\nTotal Price: {total_price:.2f}\")\n",
"\n",
" print(\"\\n--- PROGRAM FINISHED ---\")\n",
"\n",
"if __name__ == \"__main__\":\n",
" main()"
]
}
],
"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
}
Loading