Skip to content
Open
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
317 changes: 314 additions & 3 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,324 @@
" - 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"
"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",
"\n"
]
},
{
"cell_type": "markdown",
"id": "b1afe576",
"metadata": {},
"source": [
"# **LAB SOLUTIONS:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "faea089b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Quantity cannot be negative. Please enter a valid quantity.\n",
"Quantity cannot be negative. Please enter a valid quantity.\n",
"Quantity cannot be negative. Please enter a valid quantity.\n",
"Initialized Inventory: {'apple': 4, 'banana': 5, 'orange': 6}\n"
]
}
],
"source": [
"# Step 1: Define the function for initializing the inventory with error handling\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",
"# example usage\n",
"products = ['apple', 'banana', 'orange']\n",
"inventory = initialize_inventory(products)\n",
"print(\"Initialized Inventory:\", inventory)\n",
"# This script initializes an inventory for a list of products by prompting the user for quantities.\n",
"# It includes error handling to ensure valid input is provided.\n",
"# The inventory is stored in a dictionary with product names as keys and quantities as values."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8666625e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input. Please enter a numeric value for the price.\n",
"Price must be greater than zero. Please enter a valid price.\n",
"Price must be greater than zero. Please enter a valid price.\n",
"The price entered for apple is: 5.0\n",
"The price entered for banana is: 8.0\n",
"Invalid input. Please enter a numeric value for the price.\n",
"Price must be greater than zero. Please enter a valid price.\n",
"The price entered for orange is: 9.0\n",
"Total Price: 22.0\n"
]
}
],
"source": [
"# Step 2: copy here the function calculate_total_price from the lab-python-list-comprehension exercise\n",
"def calculate_total_price(customer_orders):\n",
" total_price = sum(\n",
" float(input(f\"Enter the price of {product}: \"))\n",
" for product in customer_orders\n",
" )\n",
" return total_price\n",
"\n",
"# Integrate error handling into the calculate_total_price function\n",
"# If the user enters an invalid price (e.g., a negative value or a non-numeric value), \n",
"# 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 \n",
"# and continue prompting the user until a valid price is entered.\n",
"# price cannot be zero or negative\n",
"# for each product print the price entered\n",
"# print (\"Total Price:\", calculate_total_price(customer_orders))\n",
"\n",
"def calculate_total_price(customer_orders):\n",
" total_price = 0.0\n",
" for product in customer_orders:\n",
" valid_input = False\n",
" while not valid_input:\n",
" try:\n",
" price = float(input(f\"Enter the price of {product}: \"))\n",
" if price > 0:\n",
" print(f\"The price entered for {product} is: {price}\")\n",
" total_price += price\n",
" valid_input = True\n",
" else:\n",
" print(\"Price must be greater than zero. Please enter a valid price.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a numeric value for the price.\")\n",
" return total_price\n",
"\n",
"# example usage\n",
"customer_orders = ['apple', 'banana', 'orange']\n",
"total = calculate_total_price(customer_orders)\n",
"print(\"Total Price:\", total)\n"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "b4099934",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid product name or out of stock. Please enter a valid product from the inventory: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n",
"Invalid product name or out of stock. Please enter a valid product from the inventory: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n",
"Customer Orders: {'book', 't-shirt', 'mug'}\n"
]
}
],
"source": [
"# Step 3: copy here the function get_customer_orders from the lab-python-list-comprehension exercise\n",
"def get_customer_orders():\n",
" num_orders = int(input(\"Enter the number of customer orders: \"))\n",
" \n",
" customer_orders = {\n",
" input(\"Enter the name of a product that a customer wants to order: \")\n",
" .strip().lower()\n",
" for _ in range(num_orders)\n",
" }\n",
" return customer_orders\n",
"\n",
"# Integrate error handling into the get_customer_orders function\n",
"# If the user enters an invalid number of orders (e.g., a negative value or a non-numeric value), \n",
"# 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), \n",
"# or that doesn't have stock available, display an error message and ask them to re-enter the product name. \n",
"# Hint: you will need to pass inventory as a parameter to the get_customer_orders function.\n",
"# Use a try-except block to handle the error and continue prompting the user until a valid product name is entered.\n",
"# define inventory for testing\n",
"\n",
"inventory = {'t-shirt': 10, 'mug': 5, 'hat': 0, 'book': 8, 'keychain': 15}\n",
"\n",
"def get_customer_orders(inventory):\n",
" valid_num_orders = False\n",
" while not valid_num_orders:\n",
" try:\n",
" num_orders = int(input(\"Enter the number of customer orders: \"))\n",
" if num_orders >= 0:\n",
" valid_num_orders = True\n",
" else:\n",
" print(\"Number of orders cannot be negative. Please enter a valid number.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid number.\")\n",
" \n",
" customer_orders = set()\n",
" while len(customer_orders) < num_orders:\n",
" product_name = input(\"Enter the name of a product that a customer wants to order: \").strip().lower()\n",
" if product_name in inventory and inventory[product_name] > 0:\n",
" customer_orders.add(product_name)\n",
" else:\n",
" print(f\"Invalid product name or out of stock. Please enter a valid product from the inventory: {list(inventory.keys())}\")\n",
" \n",
" return customer_orders\n",
"\n",
"# example usage\n",
"\n",
"customer_orders = get_customer_orders(inventory)\n",
"print(\"Customer Orders:\", customer_orders)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2d03701a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input. Please enter a valid number.\n",
"Invalid product name or out of stock. Please enter a valid product from the inventory: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n",
"Invalid product name or out of stock. Please enter a valid product from the inventory: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n",
"\n",
"Customer Orders: {'book', 't-shirt', 'mug'}\n",
"\n",
"The price entered for book is: 3.0\n",
"\n",
"The price entered for t-shirt is: 5.0\n",
"\n",
"The price entered for mug is: 10.0\n",
"\n",
"Total Price: 18.0\n",
"\n",
"Order Summary:\n",
"Number of different products ordered: 3\n",
"Products ordered: book, t-shirt, mug\n",
"\n",
"Inventory after the order:\n",
"t-shirt: 9 items left\n",
"mug: 4 items left\n",
"hat: 0 items left\n",
"book: 7 items left\n",
"keychain: 15 items left\n"
]
}
],
"source": [
"# Try to run the complete flow\n",
"\n",
"inventory = {'t-shirt': 10, 'mug': 5, 'hat': 0, 'book': 8, 'keychain': 15}\n",
"\n",
"def get_customer_orders(inventory):\n",
" valid_num_orders = False\n",
" while not valid_num_orders:\n",
" try:\n",
" num_orders = int(input(\"Enter the number of customer orders: \"))\n",
" if num_orders >= 0:\n",
" valid_num_orders = True\n",
" else:\n",
" print(\"Number of orders cannot be negative. Please enter a valid number.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid number.\")\n",
" \n",
" customer_orders = set()\n",
" while len(customer_orders) < num_orders:\n",
" product_name = input(\"Enter the name of a product that a customer wants to order: \").strip().lower()\n",
" if product_name in inventory and inventory[product_name] > 0:\n",
" customer_orders.add(product_name)\n",
" else:\n",
" print(f\"Invalid product name or out of stock. Please enter a valid product from the inventory: {list(inventory.keys())}\")\n",
" \n",
" return customer_orders\n",
"\n",
"# create a customer orders set \n",
"customer_orders = get_customer_orders(inventory)\n",
"print(\"\\nCustomer Orders:\", customer_orders)\n",
"\n",
"# calculate the total price for the customer orders\n",
"\n",
"def calculate_total_price(customer_orders):\n",
" total_price = 0.0\n",
" for product in customer_orders:\n",
" valid_input = False\n",
" while not valid_input:\n",
" try:\n",
" price = float(input(f\"Enter the price of {product}: \"))\n",
" if price > 0:\n",
" print(f\"\\nThe price entered for {product} is: {price}\")\n",
" total_price += price\n",
" valid_input = True\n",
" else:\n",
" print(\"Price must be greater than zero. Please enter a valid price.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a numeric value for the price.\")\n",
" return total_price\n",
"\n",
"total = calculate_total_price(customer_orders)\n",
"print(\"\\nTotal Price:\", total)\n",
"\n",
"# print statistics about the order\n",
"print(\"\\nOrder Summary:\")\n",
"print(f\"Number of different products ordered: {len(customer_orders)}\")\n",
"print(f\"Products ordered: {', '.join(customer_orders)}\")\n",
"\n",
"# print number of items left in inventory after the order\n",
"print(\"\\nInventory after the order:\")\n",
"for product in inventory:\n",
" if product in customer_orders:\n",
" inventory[product] -= 1 # assuming one item per product ordered\n",
" print(f\"{product}: {inventory[product]} items left\")\n"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "6a99cd76",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid product name or out of stock. Please enter a valid product from the inventory: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n",
"Invalid product name or out of stock. Please enter a valid product from the inventory: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n",
"Total Price: 18.0\n"
]
}
],
"source": [
"# call the functions in a complete flow\n",
"inventory = {'t-shirt': 10, 'mug': 5, 'hat': 0, 'book': 8, 'keychain': 15}\n",
"customer_orders = get_customer_orders(inventory)\n",
"total = calculate_total_price(customer_orders)\n",
"print(\"Total Price:\", total)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "base",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +401,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.5"
}
},
"nbformat": 4,
Expand Down