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
337 changes: 334 additions & 3 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,344 @@
"\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": "fc5a97c7-ccac-4b2f-9f20-5f94d0e089ec",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the initial quantities:\n",
"\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity of t-shirt: 25\n",
"Enter the quantity of mug: 5\n",
"Enter the quantity of hat: 13\n",
"Enter the quantity of book: 8\n",
"Enter the quantity of keychain: 9\n",
"\n",
"Enter the number of customer orders: 7\n",
"\n",
"Enter a product name: 3\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Only letters, spaces and hyphens allowed.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"\n",
"Enter a product name: casa\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Product not found. Available products:\n",
"t-shirt, mug, hat, book, keychain\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"\n",
"Enter a product name: mug\n",
"\n",
"Enter a product name: hat\n",
"\n",
"Enter a product name: bok\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Product not found. Available products:\n",
"t-shirt, mug, hat, book, keychain\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"\n",
"Enter a product name: book\n",
"\n",
"Enter a product name: t-shirt\n",
"\n",
"Enter a product name: \n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Only letters, spaces and hyphens allowed.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"\n",
"Enter a product name: keychain\n",
"\n",
"Enter a product name: book\n",
"\n",
"Enter a product name: mug\n",
"Enter the price for hat: 50\n",
"Enter the price for t-shirt: 15\n",
"Enter the price for keychain: 84\n",
"Enter the price for mug: dos\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: could not convert string to float: 'dos'. Please enter a valid price (e.g., 5.99).\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the price for mug: 73\n",
"Enter the price for book: 1.85\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Order Statistics\n",
"Total Products Ordered: 5\n",
"Percentage of Unique Products Ordered: 100.00%\n",
"\n",
"Updated Inventory:\n",
"t-shirt: 24\n",
"mug: 4\n",
"hat: 12\n",
"book: 7\n",
"keychain: 8\n",
"\n",
"Total Price: 223.85\n"
]
}
],
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"\n",
"# -------------------------------------------------------------------\n",
"# 1. Initialize inventory with error handling\n",
"# -------------------------------------------------------------------\n",
"def initialize_inventory(products):\n",
" inventory = {}\n",
" print(\"Enter the initial quantities:\\n\")\n",
"\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" qty = int(input(f\"Enter the quantity of {product}: \"))\n",
"\n",
" if qty < 0:\n",
" raise ValueError(\"Quantity cannot be negative.\")\n",
"\n",
" inventory[product] = qty\n",
" break\n",
"\n",
" except ValueError as e:\n",
" print(f\"Error: {e}. Please enter a valid non-negative integer.\")\n",
"\n",
" return inventory\n",
"\n",
"\n",
"# -------------------------------------------------------------------\n",
"# Helper: validate product names (letters, spaces and hyphens only)\n",
"# -------------------------------------------------------------------\n",
"def is_valid_product_name(name):\n",
" if not name.strip():\n",
" return False\n",
"\n",
" for ch in name:\n",
" if not (ch.isalpha() or ch in [\" \", \"-\"]):\n",
" return False\n",
"\n",
" return True\n",
"\n",
"\n",
"# -------------------------------------------------------------------\n",
"# 2. Get customer orders with error handling\n",
"# -------------------------------------------------------------------\n",
"def get_customer_orders(products, inventory):\n",
"\n",
" # Validate number of orders\n",
" while True:\n",
" try:\n",
" num_str = input(\"\\nEnter the number of customer orders: \")\n",
" num_orders = int(num_str)\n",
"\n",
" if num_orders < 0:\n",
" raise ValueError(\"Number of orders cannot be negative.\")\n",
"\n",
" break\n",
" except ValueError as e:\n",
" print(f\"Error: {e}. Please enter a non-negative integer.\")\n",
"\n",
" lower_products = [p.lower() for p in products]\n",
" customer_orders = set()\n",
"\n",
" for _ in range(num_orders):\n",
" while True:\n",
" product_raw = input(\"\\nEnter a product name: \").strip()\n",
" product = product_raw.lower()\n",
"\n",
" # Character validation\n",
" if not is_valid_product_name(product_raw):\n",
" print(\"Error: Only letters, spaces and hyphens allowed.\")\n",
" continue\n",
"\n",
" # Product must exist\n",
" if product not in lower_products:\n",
" print(\"Error: Product not found. Available products:\")\n",
" print(\", \".join(products))\n",
" continue\n",
"\n",
" # Find the correct key with original case\n",
" real_key = next((p for p in inventory.keys() if p.lower() == product), None)\n",
"\n",
" # Must be in stock\n",
" if inventory.get(real_key, 0) <= 0:\n",
" print(f\"Error: {real_key} is out of stock.\")\n",
" continue\n",
"\n",
" customer_orders.add(product)\n",
" break\n",
"\n",
" return customer_orders\n",
"\n",
"\n",
"# -------------------------------------------------------------------\n",
"# 3. Calculate total price with error handling\n",
"# -------------------------------------------------------------------\n",
"def calculate_total_price(customer_orders):\n",
"\n",
" total = 0.0\n",
"\n",
" for product in customer_orders:\n",
" while True:\n",
" try:\n",
" price_str = input(f\"Enter the price for {product}: \")\n",
" price = float(price_str)\n",
"\n",
" if price < 0:\n",
" raise ValueError(\"Price cannot be negative.\")\n",
"\n",
" total += price\n",
" break\n",
"\n",
" except ValueError as e:\n",
" print(f\"Error: {e}. Please enter a valid price (e.g., 5.99).\")\n",
"\n",
" return total\n",
"\n",
"\n",
"# -------------------------------------------------------------------\n",
"# 4. Update inventory (remove zero-stock items)\n",
"# -------------------------------------------------------------------\n",
"def update_inventory(customer_orders, inventory):\n",
"\n",
" for item in customer_orders:\n",
" key = next((k for k in inventory.keys() if k.lower() == item), None)\n",
" if key:\n",
" inventory[key] -= 1\n",
"\n",
" # Remove zero/negative quantities\n",
" inventory = {p: q for p, q in inventory.items() if q > 0}\n",
" return inventory\n",
"\n",
"\n",
"# -------------------------------------------------------------------\n",
"# 5. Calculate statistics\n",
"# -------------------------------------------------------------------\n",
"def calculate_order_statistics(customer_orders, products):\n",
" total_ordered = len(customer_orders)\n",
" percentage = (total_ordered / len(products) * 100) if products else 0\n",
" return total_ordered, percentage\n",
"\n",
"\n",
"# -------------------------------------------------------------------\n",
"# 6. Print statistics\n",
"# -------------------------------------------------------------------\n",
"def print_order_statistics(stats):\n",
" print(\"\\nOrder Statistics\")\n",
" print(f\"Total Products Ordered: {stats[0]}\")\n",
" print(f\"Percentage of Unique Products Ordered: {stats[1]:.2f}%\")\n",
"\n",
"\n",
"# -------------------------------------------------------------------\n",
"# 7. Print updated inventory\n",
"# -------------------------------------------------------------------\n",
"def print_updated_inventory(inventory):\n",
" print(\"\\nUpdated Inventory:\")\n",
"\n",
" if not inventory:\n",
" print(\"All items are out of stock.\")\n",
" return\n",
"\n",
" for product, qty in inventory.items():\n",
" print(f\"{product}: {qty}\")\n",
"\n",
"\n",
"# ===================================================================\n",
"# Program Execution\n",
"# ===================================================================\n",
"\n",
"inventory = initialize_inventory(products)\n",
"customer_orders = get_customer_orders(products, inventory)\n",
"total_price = calculate_total_price(customer_orders)\n",
"inventory = update_inventory(customer_orders, inventory)\n",
"stats = calculate_order_statistics(customer_orders, products)\n",
"\n",
"print_order_statistics(stats)\n",
"print_updated_inventory(inventory)\n",
"\n",
"print(f\"\\nTotal Price: {total_price:.2f}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "121bf43d-dbfc-4b54-a79d-57eee5d512d8",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python [conda env:base] *",
"language": "python",
"name": "python3"
"name": "conda-base-py"
},
"language_info": {
"codemirror_mode": {
Expand All @@ -90,7 +421,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.5"
}
},
"nbformat": 4,
Expand Down