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
172 changes: 172 additions & 0 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,178 @@
"\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": "7ddfa8ca-a31b-4d0d-89c5-b828af5a1071",
"metadata": {},
"source": [
"**1.** `initialize_inventory(products)` \u2014 the retry loop given in the instructions above. Can't stay a one-line dict comprehension anymore: each product needs its own retry loop, so it's back to a regular loop with `try/except` inside."
]
},
{
"cell_type": "code",
"id": "f70e78cc-b7f0-4b90-97d4-deaf8ac96168",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"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(\"Quantity cannot be negative.\")\n",
" valid_quantity = True\n",
" except ValueError as error:\n",
" print(f\"Error: {error}\")\n",
" inventory[product] = quantity\n",
" return inventory"
]
},
{
"cell_type": "markdown",
"id": "8244da3f-b0e8-4dc1-96dd-281ebb5f0d21",
"metadata": {},
"source": [
"**2.** `calculate_total_price(customer_orders)` \u2014 same retry pattern per product. `float(...)` raises `ValueError` on its own for non-numeric input, so the `except` catches both that and the explicit `raise` for negative prices."
]
},
{
"cell_type": "code",
"id": "cd7040f6-e212-4d91-ac72-a99d989cd751",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"def calculate_total_price(customer_orders):\n",
" total_price = 0\n",
" for product in customer_orders:\n",
" valid_price = False\n",
" while not valid_price:\n",
" try:\n",
" price = float(input(f\"Enter the price of {product}: \"))\n",
" if price < 0:\n",
" raise ValueError(\"Price cannot be negative.\")\n",
" valid_price = True\n",
" except ValueError as error:\n",
" print(f\"Error: {error}\")\n",
" total_price += price\n",
" return total_price"
]
},
{
"cell_type": "markdown",
"id": "a94753a1-890b-4e39-b289-45e27ea2bb49",
"metadata": {},
"source": [
"**3.** `get_customer_orders(inventory)` \u2014 now takes `inventory` as a parameter (per the hint) so it can check a product actually exists and has stock. Two separate validation loops: one for `num_orders` (numeric, non-negative), one for the product names themselves."
]
},
{
"cell_type": "code",
"id": "3071fe8f-bbe0-4ac8-a727-7b7b6a709d7b",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"def get_customer_orders(inventory):\n",
" valid_number = False\n",
" while not valid_number:\n",
" try:\n",
" num_orders = int(input(\"Enter the number of customer orders: \"))\n",
" if num_orders < 0:\n",
" raise ValueError(\"Number of orders cannot be negative.\")\n",
" valid_number = True\n",
" except ValueError as error:\n",
" print(f\"Error: {error}\")\n",
"\n",
" customer_orders = set()\n",
" while len(customer_orders) < num_orders:\n",
" product = input(\"Enter the name of a product that a customer wants to order: \")\n",
" if product not in inventory:\n",
" print(f\"Error: '{product}' is not a valid product.\")\n",
" elif inventory[product] <= 0:\n",
" print(f\"Error: '{product}' is out of stock.\")\n",
" else:\n",
" customer_orders.add(product)\n",
" return customer_orders"
]
},
{
"cell_type": "markdown",
"id": "d3b2b2a9-0850-4a48-bd23-300a54fcfb9d",
"metadata": {},
"source": [
"**4.** The rest \u2014 `update_inventory`, `calculate_order_statistics` and the two `print_*` helpers \u2014 are unchanged from the comprehension lab, no invalid input to guard against there. `get_customer_orders` now needs `inventory` passed in."
]
},
{
"cell_type": "code",
"id": "9f22a73f-ac0e-47c3-b096-e1fb6be42c2d",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"def update_inventory(customer_orders, inventory):\n",
" updated_inventory = {\n",
" product: (quantity - 1 if product in customer_orders else quantity)\n",
" for product, quantity in inventory.items()\n",
" if product not in customer_orders or quantity - 1 > 0\n",
" }\n",
" return updated_inventory\n",
"\n",
"\n",
"def calculate_order_statistics(customer_orders, products):\n",
" total_products_ordered = len(customer_orders)\n",
" percentage_ordered = (total_products_ordered / len(products)) * 100\n",
" return total_products_ordered, percentage_ordered\n",
"\n",
"\n",
"def print_order_statistics(order_statistics):\n",
" print(\"\\nOrder Statistics:\")\n",
" print(f\"Total Products Ordered: {order_statistics[0]}\")\n",
" print(f\"Percentage of Unique Products Ordered: {order_statistics[1]}\")\n",
"\n",
"\n",
"def print_updated_inventory(inventory):\n",
" print(\"\\nUpdated Inventory:\")\n",
" for product, quantity in inventory.items():\n",
" print(f\"{product}: {quantity}\")"
]
},
{
"cell_type": "markdown",
"id": "c2b55085-020e-4905-8605-e16fa3c61dd7",
"metadata": {},
"source": [
"**5.** Call everything in sequence \u2014 same order as the comprehension lab, `get_customer_orders` just needs `inventory` passed in now."
]
},
{
"cell_type": "code",
"id": "cb3c410f-94e3-4c61-9026-e3a87a824029",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"inventory = initialize_inventory(products)\n",
"customer_orders = get_customer_orders(inventory)\n",
"\n",
"order_statistics = calculate_order_statistics(customer_orders, products)\n",
"print_order_statistics(order_statistics)\n",
"\n",
"inventory = update_inventory(customer_orders, inventory)\n",
"print_updated_inventory(inventory)\n",
"\n",
"total_price = calculate_total_price(customer_orders)\n",
"print(f\"Total Price: {total_price}\")"
]
}
],
"metadata": {
Expand Down