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
195 changes: 193 additions & 2 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,202 @@
"\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": "714ea21a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"=== Initialize Inventory ===\n",
"\n",
"=== Take Customer Orders ===\n",
"Error: invalid literal for int() with base 10: 't-shirt' Please enter 0 or a positive integer.\n",
"Error: invalid literal for int() with base 10: 'mug' Please enter 0 or a positive integer.\n",
"\n",
"Order Statistics:\n",
"Total Products Ordered: 3\n",
"Percentage of Unique Products Ordered: 60.0\n",
"\n",
"=== Update Inventory ===\n",
"- 'mug' deducted by 1. New stock: 4\n",
"- 't-shirt' deducted by 1. New stock: 4\n",
"- 'keychain' deducted by 1. New stock: 4\n",
"\n",
"Updated Inventory:\n",
"t-shirt: 4\n",
"mug: 4\n",
"hat: 5\n",
"book: 5\n",
"keychain: 4\n",
"\n",
"Total Price: 35.0\n"
]
}
],
"source": [
"def initialize_inventory(products):\n",
" \"\"\"\n",
" Ask the user for a starting quantity for each product.\n",
" Validates: integer, non-negative.\n",
" \"\"\"\n",
" inventory = {}\n",
" print(\"\\n=== Initialize Inventory ===\")\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" raw = input(f\"Enter the quantity of {product}s available: \")\n",
" qty = int(raw)\n",
" if qty < 0:\n",
" raise ValueError(\"Quantity cannot be negative.\")\n",
" inventory[product] = qty\n",
" break\n",
" except ValueError as err:\n",
" print(f\"Error: {err} Please enter a non-negative integer.\")\n",
" return inventory\n",
"\n",
"\n",
"def get_customer_orders(inventory):\n",
" \"\"\"\n",
" Ask how many orders to take (validated), then collect product names.\n",
" Validates: product must exist in inventory AND have stock > 0.\n",
" Returns a set of unique product names (1 unit max per product).\n",
" \"\"\"\n",
" print(\"\\n=== Take Customer Orders ===\")\n",
" # Validate number of orders\n",
" while True:\n",
" try:\n",
" raw = input(\"Enter the number of customer orders: \")\n",
" n = int(raw)\n",
" if n < 0:\n",
" raise ValueError(\"Number of orders cannot be negative.\")\n",
" break\n",
" except ValueError as err:\n",
" print(f\"Error: {err} Please enter 0 or a positive integer.\")\n",
"\n",
" orders = set()\n",
" i = 0\n",
" while i < n:\n",
" name = input(\"Enter the name of a product that a customer wants to order: \").strip().lower()\n",
" if name not in inventory:\n",
" print(f\"Error: '{name}' is not in the inventory. Available: {', '.join(inventory.keys()) or '(none)'}\")\n",
" continue\n",
" if inventory[name] <= 0:\n",
" print(f\"Error: '{name}' is out of stock. Choose another product.\")\n",
" continue\n",
"\n",
" # if already ordered (set), we still allow but it won’t double-count;\n",
" # if you prefer to forbid duplicates, uncomment next two lines:\n",
" # if name in orders:\n",
" # print(\"That product is already in the order (1 unit per product). Choose another.\"); continue\n",
"\n",
" orders.add(name)\n",
" i += 1\n",
"\n",
" return orders\n",
"\n",
"\n",
"def update_inventory(customer_orders, inventory):\n",
" \"\"\"\n",
" Deduct 1 per ordered product if stock is available.\n",
" Then remove zero-stock items with a dict comprehension.\n",
" \"\"\"\n",
" print(\"\\n=== Update Inventory ===\")\n",
" for item in customer_orders:\n",
" if item in inventory and inventory[item] > 0:\n",
" inventory[item] -= 1\n",
" print(f\"- '{item}' deducted by 1. New stock: {inventory[item]}\")\n",
" else:\n",
" # Shouldn't happen due to validation, but keep it safe\n",
" print(f\"- '{item}' not deducted (not found or no stock).\")\n",
"\n",
" # Filter out zero-quantity products\n",
" inventory = {k: v for k, v in inventory.items() if v > 0}\n",
" return inventory\n",
"\n",
"\n",
"def calculate_order_statistics(customer_orders, products):\n",
" \"\"\"\n",
" Compute total unique products ordered and percentage vs catalog size.\n",
" \"\"\"\n",
" total_unique = len(customer_orders)\n",
" percent_unique = (total_unique / len(products) * 100) if products else 0.0\n",
" return total_unique, percent_unique\n",
"\n",
"\n",
"def print_order_statistics(order_statistics):\n",
" total_unique, percent_unique = order_statistics\n",
" print(\"\\nOrder Statistics:\")\n",
" print(f\"Total Products Ordered: {total_unique}\")\n",
" print(f\"Percentage of Unique Products Ordered: {percent_unique:.1f}\")\n",
"\n",
"\n",
"def print_updated_inventory(inventory):\n",
" \"\"\"\n",
" Print inventory (or a message if empty).\n",
" \"\"\"\n",
" print(\"\\nUpdated Inventory:\")\n",
" if not inventory:\n",
" print(\"(All items are out of stock.)\")\n",
" return\n",
" print(\"\\n\".join(f\"{k}: {v}\" for k, v in inventory.items()))\n",
"\n",
"\n",
"def calculate_total_price(customer_orders):\n",
" \"\"\"\n",
" Prompt for price of each ordered product and sum them.\n",
" Validates: float, non-negative.\n",
" Returns the total price (float).\n",
" \"\"\"\n",
" print()\n",
" prices = {}\n",
" for item in customer_orders:\n",
" while True:\n",
" try:\n",
" raw = input(f\"Enter the price of {item}: \")\n",
" price = float(raw)\n",
" if price < 0:\n",
" raise ValueError(\"Price cannot be negative.\")\n",
" prices[item] = price\n",
" break\n",
" except ValueError as err:\n",
" print(f\"Error: {err} Please enter a non-negative number (e.g., 0, 5, 10.5).\")\n",
" return sum(prices.values())\n",
"\n",
"\n",
"if __name__ == \"__main__\":\n",
" products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
" inventory = initialize_inventory(products)\n",
" customer_orders = get_customer_orders(inventory)\n",
"\n",
" stats = calculate_order_statistics(customer_orders, products)\n",
" print_order_statistics(stats)\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:.1f}\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1b9a413c",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +281,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.9.6"
}
},
"nbformat": 4,
Expand Down