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
149 changes: 147 additions & 2 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,156 @@
"\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": "2bc83271",
"metadata": {},
"outputs": [],
"source": [
"#1\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"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ae145bc2",
"metadata": {},
"outputs": [],
"source": [
"#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",
"def calculate_total_price(products):\n",
" prices = {}\n",
" for product in products:\n",
" valid_price = False\n",
" while not valid_price:\n",
" try:\n",
" price = float(input(f\"Enter the price of one {product}: \"))\n",
" if price >= 0:\n",
" prices[product] = price\n",
" valid_price = True\n",
" else:\n",
" print(\"Price cannot be negative. Please enter a valid price.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a number.\")\n",
" return prices\n",
"\n",
"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4d789222",
"metadata": {},
"outputs": [],
"source": [
"#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",
"def get_customer_orders(inventory):\n",
" orders = {}\n",
"\n",
" # Get number of orders\n",
" while True:\n",
" try:\n",
" num_orders = int(input(\"How many products would you like to order? \"))\n",
" if num_orders > 0:\n",
" break\n",
" else:\n",
" print(\"Please enter a positive number of orders.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a number.\")\n",
"\n",
" # Get each order\n",
" for i in range(num_orders):\n",
" while True:\n",
" product = input(f\"Enter the name of product #{i+1}: \").strip().lower()\n",
" if product in inventory:\n",
" if inventory[product] > 0:\n",
" break\n",
" else:\n",
" print(f\"Sorry, {product} is out of stock. Choose another product.\")\n",
" else:\n",
" print(\"Invalid product name. Please choose from the available inventory.\")\n",
"\n",
" while True:\n",
" try:\n",
" quantity = int(input(f\"Enter the quantity of {product} you want to order: \"))\n",
" if 0 < quantity <= inventory[product]:\n",
" orders[product] = quantity\n",
" inventory[product] -= quantity\n",
" break\n",
" elif quantity <= 0:\n",
" print(\"Quantity must be greater than 0.\")\n",
" else:\n",
" print(f\"Only {inventory[product]} {product}(s) available.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a number.\")\n",
" \n",
" return orders\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9f93144d",
"metadata": {},
"outputs": [],
"source": [
"#4. Test your code by running the program and deliberately entering invalid quantities and product names. Make sure the error handling mechanism \n",
"# works as expected.\n",
"\n",
"def main():\n",
" products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
" inventory = initialize_inventory(products)\n",
" customer_orders = get_customer_orders(inventory)\n",
"\n",
" print(\"\\nOrder Statistics:\")\n",
" print(f\"Total Products Ordered: {len(customer_orders)}\")\n",
" percentage = (len(customer_orders) / len(inventory)) * 100\n",
" print(f\"Percentage of Unique Products Ordered: {percentage:.1f}%\")\n",
"\n",
" print(\"\\nUpdated Inventory:\")\n",
" for product, qty in inventory.items():\n",
" print(f\"{product}: {qty}\")\n",
"\n",
" prices = calculate_total_price(customer_orders)\n",
" print(f\"\\nPrices entered: {prices}\")\n",
"\n",
"\n",
"# Run the program\n",
"if __name__ == \"__main__\":\n",
" main()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +235,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.12.9"
}
},
"nbformat": 4,
Expand Down