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
98 changes: 98 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
{
"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"
]
}
],
"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"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
223 changes: 221 additions & 2 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,225 @@
"# Lab | Error Handling"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "61cc5453",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Inventory\n",
"Invalid input. Please enter an integer quantity.\n",
"\n",
"Customer order:\n",
"Invalid input. Please enter a whole number.\n",
"Invalid input. Please enter a whole number.\n",
"Invalid input. Please enter a whole number.\n",
"Unknown product. Please enter a valid product name.\n",
"Available products: t-shirt, mug, hat, book, keychain\n",
"Unknown product. Please enter a valid product name.\n",
"Available products: t-shirt, mug, hat, book, keychain\n",
"Unknown product. Please enter a valid product name.\n",
"Available products: t-shirt, mug, hat, book, keychain\n",
"Unknown product. Please enter a valid product name.\n",
"Available products: t-shirt, mug, hat, book, keychain\n",
"Unknown product. Please enter a valid product name.\n",
"Available products: t-shirt, mug, hat, book, keychain\n",
"Unknown product. Please enter a valid product name.\n",
"Available products: t-shirt, mug, hat, book, keychain\n",
"Unknown product. Please enter a valid product name.\n",
"Available products: t-shirt, mug, hat, book, keychain\n",
"Unknown product. Please enter a valid product name.\n",
"Available products: t-shirt, mug, hat, book, keychain\n",
"Unknown product. Please enter a valid product name.\n",
"Available products: t-shirt, mug, hat, book, keychain\n",
"\n",
"Price input for each ordered product:\n",
"\n",
"Order Statistics:\n",
"Total Products Ordered: 2\n",
"Percentage of Products Ordered: 40.0\n",
"\n",
"Updated Inventory\n",
"t-shirt: 5\n",
"mug: 4\n",
"hat: 5\n",
"book: 8\n",
"keychain: 5\n",
"\n",
"Total price of the customer order: 25.0\n"
]
}
],
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"\n",
"# Step 1: Define the function for initializing the inventory with error handling:\n",
"\n",
"\n",
"def initialize_inventory(products):\n",
" print(\"\\nInventory\")\n",
" inventory = {}\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" quantity = int(input(f\"Enter the available quantity for {product}: \"))\n",
" if quantity < 0:\n",
" print(\"Quantity cannot be negative. Please enter a valid quantity.\")\n",
" continue\n",
" inventory[product] = quantity\n",
" break\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter an integer quantity.\")\n",
" return inventory\n",
"\n",
" \n",
"\n",
"\n",
"\n",
"def get_customer_orders():\n",
" print(\"\\nCustomer order:\")\n",
"\n",
" num_orders = int(input(\"How many products does the customer want to order? \"))\n",
"\n",
" # list:\n",
" choice_orders = [\n",
" input(f\"Enter the name of product #{i + 1}: \").strip().lower()\n",
" for i in range(num_orders)\n",
" ]\n",
" \n",
" customer_orders = {product for product in choice_orders if product in products}\n",
"\n",
" return customer_orders\n",
"\n",
"\n",
"# Step 2. Modify the `calculate_total_price` function to include error handling:\n",
"\n",
"def get_customer_orders(inventory):\n",
" print(\"\\nCustomer order:\")\n",
"\n",
" while True:\n",
" try:\n",
" num_orders = int(input(\"How many products does the customer want to order? \"))\n",
" if num_orders < 0:\n",
" print(\"Number of products cannot be negative. Please enter a valid number.\")\n",
" continue\n",
" break\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a whole number.\")\n",
"\n",
" choice_orders = []\n",
"\n",
" for i in range(num_orders):\n",
" while True:\n",
" product = input(f\"Enter the name of product #{i + 1}: \").strip().lower()\n",
"\n",
" if product not in products:\n",
" print(\"Unknown product. Please enter a valid product name.\")\n",
" print(f\"Available products: {', '.join(products)}\")\n",
" continue\n",
"\n",
" if inventory.get(product, 0) <= 0:\n",
" print(f\"No stock available for '{product}'. Please choose another product.\")\n",
" continue\n",
"\n",
" choice_orders.append(product)\n",
" break\n",
"\n",
" customer_orders = {product for product in choice_orders if product in products}\n",
" return customer_orders\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"def update_inventory(customer_orders, inventory):\n",
" updated_inventory = {\n",
" product: (quantity - 1 if product in customer_orders and quantity > 0 else quantity)\n",
" for product, quantity in inventory.items()\n",
" }\n",
"\n",
" updated_inventory = {\n",
" product: quantity\n",
" for product, quantity in updated_inventory.items()\n",
" if quantity > 0\n",
" }\n",
"\n",
" return updated_inventory\n",
"\n",
"\n",
"\n",
"def calculate_order_statistics(customer_orders, products):\n",
" total_products_ordered = len(customer_orders)\n",
" percentage_ordered = (total_products_ordered / len(products)) * 100\n",
" return total_products_ordered, percentage_ordered\n",
"\n",
"\n",
"def print_order_statistics(order_statistics):\n",
" total_products_order, percentage_order = order_statistics\n",
"\n",
" print(\"\\nOrder Statistics:\")\n",
" print(f\"Total Products Ordered: {total_products_order}\")\n",
" print(f\"Percentage of Products Ordered: {percentage_order:}\")\n",
"\n",
"\n",
"\n",
"def print_updated_inventory(inventory):\n",
" print(\"\\nUpdated Inventory\")\n",
"\n",
" [print(f\"{product}: {quantity}\") for product, quantity in inventory.items()]\n",
"\n",
"\n",
"\n",
"\n",
"# Stp 3. Modify the `get_customer_orders` function to include error handling:\n",
"\n",
"def calculate_total_price(customer_orders):\n",
" print(\"\\nPrice input for each ordered product:\")\n",
"\n",
" total_price = 0.0\n",
"\n",
" for product in customer_orders:\n",
" while True:\n",
" try:\n",
" price = float(input(f\"Enter the price for '{product}': \"))\n",
" if price < 0:\n",
" print(\"Price cannot be negative. Please enter a valid price.\")\n",
" continue\n",
" total_price += price\n",
" break\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a numeric price.\")\n",
"\n",
" return total_price\n",
"\n",
"\n",
"\n",
"def total_price_order():\n",
" inventory = initialize_inventory(products)\n",
" customer_orders = get_customer_orders(inventory)\n",
"\n",
" order_stats = calculate_order_statistics(customer_orders, products)\n",
"\n",
" total_price = calculate_total_price(customer_orders)\n",
"\n",
" inventory = update_inventory(customer_orders, inventory)\n",
"\n",
" print_order_statistics(order_stats)\n",
" print_updated_inventory(inventory)\n",
"\n",
" print(f\"\\nTotal price of the customer order: {total_price:.1f}\")\n",
"\n",
"\n",
"if __name__ == \"__main__\":\n",
" total_price_order()\n"
]
},
{
"cell_type": "markdown",
"id": "bc99b386-7508-47a0-bcdb-d969deaf6c8b",
Expand Down Expand Up @@ -76,7 +295,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "base",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +309,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.5"
}
},
"nbformat": 4,
Expand Down