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
386 changes: 386 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,386 @@
{
"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": "markdown",
"id": "a8ae339d-1806-45a0-a3a4-47850dc43df6",
"metadata": {},
"source": [
"1. Define the function for initializing the inventory with error handling"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "1a34bb37-3f22-4a28-bb80-f7ba7b1ec887",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity of t-shirts available: 10\n",
"Enter the quantity of mugs available: 19\n",
"Enter the quantity of hats available: 10\n",
"Enter the quantity of books available: 10\n",
"Enter the quantity of keychains available: 10\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"['t-shirt', 'mug', 'hat', 'book', 'keychain']\n"
]
}
],
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\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",
"inventory = initialize_inventory(products)\n",
"print(products)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "882807d3-ff8a-424f-af82-a370d7eb7894",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['t-shirt', 'mug', 'hat', 'book', 'keychain']"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"products"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "2c6ad392-42a1-49c1-9b91-65d9825f0951",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'t-shirt': 10, 'mug': 19, 'hat': 10, 'book': 10, 'keychain': 10}"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inventory"
]
},
{
"cell_type": "markdown",
"id": "079f3c4d-c2de-4cf2-9cc5-219d7011da50",
"metadata": {},
"source": [
"2. Modify the calculate_total_price function to include error handling.\n",
"\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"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "02fda518-d0ec-4721-bbe0-98a51a4e12d3",
"metadata": {},
"outputs": [],
"source": [
"total_products_ordered={'t-shirt': 3, 'mug': 1}"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "ee5d6ead-5aa6-4191-9073-de3499ba55a2",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Unit price of t-shirt: 4\n",
"Unit price of mug: 5\n",
"Unit price of hat: 6\n",
"Unit price of book: 7\n",
"Unit price of keychain: 8\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"17\n",
"{'t-shirt': 4, 'mug': 5, 'hat': 6, 'book': 7, 'keychain': 8}\n"
]
}
],
"source": [
"def calculate_order_price(inventory,total_products_ordered):\n",
" inventory_cost = {}\n",
" \n",
" for product in inventory:\n",
" isValid = False\n",
" while not isValid:\n",
" try:\n",
" price = int(input(f\"Unit price of {product}: \"))\n",
" if price < 0:\n",
" raise ValueError(\"Invalid quantity! Please enter a non-negative value.\")\n",
" isValid = True\n",
" except ValueError as error:\n",
" print(f\"Error: {error}\")\n",
" inventory_cost[product]= price\n",
"\n",
" cost_of_order = sum(inventory_cost[product] * quantity for product,quantity in total_products_ordered.items())\n",
" \n",
" return cost_of_order,inventory_cost\n",
"\n",
"cost_of_order, inventory_cost = calculate_order_price(inventory,total_products_ordered)\n",
"\n",
"print(cost_of_order)\n",
"print(inventory_cost)"
]
},
{
"cell_type": "markdown",
"id": "35cd3972-a91d-4d83-a608-b72826b7fb2b",
"metadata": {},
"source": [
"3. Modify the get_customer_orders function to include error handling.\n",
"\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"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "b5e5fb0f-e2ac-4922-9937-b26df98fc2a2",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"How many different products would you like to order? 2\n",
"Enter product #1: pizza\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Invalid product. Choose from: t-shirt, mug, hat, book, keychain\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter product #1: t-shirt\n",
"Quantity: 3\n",
"Enter product #2: mug\n",
"Quantity: 1\n"
]
}
],
"source": [
"def get_customer_orders():\n",
" total_products_ordered = {}\n",
"\n",
" #Ask for number of different items to order\n",
" isValid = False\n",
" while not isValid:\n",
" try:\n",
" num_orders = int(input(f\"How many different products would you like to order? \"))\n",
" if num_orders < 0:\n",
" raise ValueError(\"Invalid quantity! Please enter a non-negative value.\")\n",
" isValid = True\n",
" except ValueError as error:\n",
" print(f\"Error: {error}\")\n",
"\n",
" #Get the number of items per desired product \n",
" for i in range(num_orders):\n",
" isValid = False\n",
" while not isValid:\n",
" try:\n",
" product = input(f\"Enter product #{i + 1}: \").strip().lower()\n",
" if product not in products:\n",
" raise ValueError(f\"Invalid product. Choose from: {', '.join(products)}\")\n",
" ordered_quantity = int(input(\"Quantity: \"))\n",
" if ordered_quantity < 0:\n",
" raise ValueError(\"Invalid quantity! Please enter a non-negative value.\")\n",
" total_products_ordered[product] = ordered_quantity\n",
" isValid = True\n",
" except ValueError as error:\n",
" print(f\"Error: {error}\")\n",
" \n",
" return total_products_ordered\n",
" \n",
"#num_orders= get_customer_orders()\n",
"total_products_ordered = get_customer_orders()"
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "fd09737b-0b7e-4cc6-a83d-5db811ba17ef",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'t-shirt': 3, 'mug': 1}"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"total_products_ordered"
]
},
{
"cell_type": "markdown",
"id": "268f3130-ac56-4522-af0f-a6c6e72bad68",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "75fa4f0e-b324-4efc-976e-a6f9c52c2a69",
"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.14.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading