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
293 changes: 293 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,293 @@
{
"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": 1,
"id": "3e529a2c-34eb-441c-8b41-61cafdb0f04b",
"metadata": {},
"outputs": [],
"source": [
"def calculate_total_price(orders):\n",
" total_price = 0\n",
"\n",
" for product in orders:\n",
" valid_input = False\n",
"\n",
" while not valid_input:\n",
" try:\n",
" price = float(input(f\"Enter the price of {product}: \"))\n",
"\n",
" if price < 0:\n",
" print(\"Price cannot be negative. Please enter a valid price.\")\n",
" else:\n",
" total_price += price\n",
" valid_input = True\n",
"\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a numeric value.\")\n",
"\n",
" return total_price"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "2112e8eb-1ab8-49da-acab-1e2a6d3a9c77",
"metadata": {},
"outputs": [],
"source": [
"def get_customer_orders(inventory):\n",
" orders = []\n",
"\n",
" # Get number of orders with error handling\n",
" valid_number = False\n",
" while not valid_number:\n",
" try:\n",
" num_orders = int(input(\"How many products would you like to order? \"))\n",
"\n",
" if num_orders <= 0:\n",
" print(\"Number of orders must be a positive number.\")\n",
" else:\n",
" valid_number = True\n",
"\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid integer.\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "a0172c44-1b9f-4d7b-965a-b5a572309944",
"metadata": {},
"outputs": [],
"source": [
"# Get each product with validation\n",
"def get_orders(num_orders, inventory): # Assuming this is inside a function\n",
" orders = [] # Added this line to initialize orders list\n",
" for i in range(num_orders):\n",
" valid_product = False\n",
"\n",
" while not valid_product:\n",
" product = input(f\"Enter product name for order {i+1}: \").strip()\n",
"\n",
" if product not in inventory:\n",
" print(\"Product not found in inventory. Please enter a valid product name.\")\n",
" \n",
" elif inventory[product] <= 0:\n",
" print(\"Sorry, this product is currently out of stock. Choose another product.\")\n",
" \n",
" else:\n",
" orders.append(product)\n",
" inventory[product] -= 1 # Reduce stock after successful order\n",
" valid_product = True\n",
"\n",
" return orders # Fixed indentation to match the function level"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "3e25d063-d143-4307-a433-0ec39e56cd4d",
"metadata": {},
"outputs": [],
"source": [
"products = [\"t-shirt\", \"hat\", \"mug\", \"keychain\"]"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "b68f0ef8-6193-48c6-abd8-b934746850f0",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"How many products would you like to order? 11\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Customer Orders: None\n"
]
}
],
"source": [
"# First, define the inventory variable\n",
"inventory = {} # Replace with your actual inventory data structure\n",
" # For example: inventory = {\"item1\": 10, \"item2\": 5}\n",
"\n",
"# Then call the function with the defined inventory\n",
"orders = get_customer_orders(inventory)\n",
"print(\"\\nCustomer Orders:\", orders)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "8d19651a-dd59-4a3b-88aa-99d616d9cfff",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Total price: 0\n"
]
}
],
"source": [
"# First, make sure orders is properly defined and not None\n",
"orders = [] if orders is None else orders # Initialize to empty list if None\n",
"\n",
"# Then, ensure calculate_total_price handles empty or None inputs properly\n",
"def calculate_total_price(orders):\n",
" if not orders: # This handles both None and empty iterables\n",
" return 0 # Return a default value instead of None\n",
" \n",
" total = 0\n",
" for order in orders:\n",
" # Add proper error handling for each order\n",
" try:\n",
" # Assuming each order has a 'price' attribute or key\n",
" total += order.get('price', 0) # For dictionaries\n",
" # OR total += order.price # For objects\n",
" except (AttributeError, TypeError):\n",
" # Handle cases where order doesn't have expected structure\n",
" continue\n",
" \n",
" return total\n",
"\n",
"# Now call the function\n",
"total = calculate_total_price(orders)\n",
"print(\"\\nTotal price:\", total)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "e605145d-0464-4bdc-8c54-7d76b38d31e9",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Updated Inventory: {}\n"
]
}
],
"source": [
"print(\"\\nUpdated Inventory:\", inventory)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "145e177b-8db3-491b-82b0-e1b2ed48c7d7",
"metadata": {},
"outputs": [],
"source": []
}
],
"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