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
86 changes: 84 additions & 2 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,93 @@
"\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": "aa46ccee",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'apple': 200, 'banana': 100, 'orange': 200}\n",
"['apple', 'banana', 'orange']\n",
"37.0\n"
]
}
],
"source": [
"def initialize_inventory(products):\n",
" inventory = {}\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" quantity = int(input(f\"Enter quantity for {product}: \"))\n",
" if quantity <= 0:\n",
" raise ValueError\n",
" inventory[product] = quantity\n",
" break\n",
" except ValueError:\n",
" print(\"Error: you must enter a positive value for an order.\")\n",
" return inventory\n",
"\n",
"\n",
"def calculate_total_price(customer_orders):\n",
" total = 0\n",
" for product in customer_orders:\n",
" while True:\n",
" try:\n",
" price = float(input(f\"Enter price for {product}: \"))\n",
" if price <= 0:\n",
" raise ValueError\n",
" total += price\n",
" break\n",
" except ValueError:\n",
" print(\"Error: you must enter a positive value for price.\")\n",
" return total\n",
"\n",
"\n",
"def get_customer_orders(inventory):\n",
" orders = []\n",
" while True:\n",
" try:\n",
" n = int(input(\"Enter number of orders: \"))\n",
" if n <= 0:\n",
" raise ValueError\n",
" break\n",
" except ValueError:\n",
" print(\"Error: you must enter a positive value for an order.\")\n",
"\n",
" for _ in range(n):\n",
" while True:\n",
" product = input(\"Enter product name: \")\n",
" if product not in inventory:\n",
" print(\"Error: you must enter a valid product name.\")\n",
" elif inventory[product] <= 0:\n",
" print(\"Error: Product out of stock.\")\n",
" else:\n",
" orders.append(product)\n",
" break\n",
" \n",
" return orders\n",
"\n",
"\n",
"products = [\"apple\", \"banana\", \"orange\"]\n",
"inventory = initialize_inventory(products)\n",
"orders = get_customer_orders(inventory)\n",
"total_price = calculate_total_price(orders)\n",
"\n",
"print(inventory)\n",
"print(orders)\n",
"print(total_price)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "base",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +172,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.5"
}
},
"nbformat": 4,
Expand Down