Skip to content
Open
Show file tree
Hide file tree
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
302 changes: 302 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,302 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e",
"metadata": {},
"source": [
"# Lab | Error Handling"
]
},
{
"cell_type": "markdown",
"id": "6f8e446f-16b4-4e21-92e7-9d3d1eb551b6",
"metadata": {},
"source": [
"Objective: Practice how to identify, handle and recover from potential errors in Python code using try-except blocks."
]
},
{
"cell_type": "markdown",
"id": "e253e768-aed8-4791-a800-87add1204afa",
"metadata": {},
"source": [
"## Challenge \n",
"\n",
"Paste here your lab *functions* solutions. Apply error handling techniques to each function using try-except blocks. "
]
},
{
"cell_type": "markdown",
"id": "9180ff86-c3fe-4152-a609-081a287fa1af",
"metadata": {},
"source": [
"The try-except block in Python is designed to handle exceptions and provide a fallback mechanism when code encounters errors. By enclosing the code that could potentially throw errors in a try block, followed by specific or general exception handling in the except block, we can gracefully recover from errors and continue program execution.\n",
"\n",
"However, there may be cases where an input may not produce an immediate error, but still needs to be addressed. In such situations, it can be useful to explicitly raise an error using the \"raise\" keyword, either to draw attention to the issue or handle it elsewhere in the program.\n",
"\n",
"Modify the code to handle possible errors in Python, it is recommended to use `try-except-else-finally` blocks, incorporate the `raise` keyword where necessary, and print meaningful error messages to alert users of any issues that may occur during program execution.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "cc2c441d-9dcf-4817-b097-cf6cbe440846",
"metadata": {},
"outputs": [],
"source": [
"# -------------------------------------------\n",
"# Challenge: Error Handling for Lab Functions\n",
"# -------------------------------------------\n",
"\n",
"# 1. initialize_inventory\n",
"def initialize_inventory(products):\n",
" inventory = {}\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" quantity = input(f\"Enter the quantity of {product}s available: \")\n",
"\n",
" # Try converting to integer\n",
" quantity = int(quantity)\n",
"\n",
" # Raise custom error\n",
" if quantity < 0:\n",
" raise ValueError(\"Quantity cannot be negative.\")\n",
"\n",
" except ValueError as error:\n",
" print(f\"❌ Error: {error}. Please enter a valid non-negative number.\")\n",
" else:\n",
" # Executes only if no error occurred\n",
" inventory[product] = quantity\n",
" break\n",
" finally:\n",
" pass # You could log attempts here\n",
"\n",
" return inventory\n",
"\n",
"\n",
"\n",
"# 2. calculate_total_price\n",
"def calculate_total_price(products):\n",
" prices = {}\n",
"\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" price = input(f\"Enter the price for {product}: \")\n",
"\n",
" # Convert to float\n",
" price = float(price)\n",
"\n",
" # Validate\n",
" if price < 0:\n",
" raise ValueError(\"Price cannot be negative.\")\n",
"\n",
" except ValueError as error:\n",
" print(f\"❌ Error: {error}. Please enter a valid non-negative number.\")\n",
" else:\n",
" prices[product] = price\n",
" break\n",
" finally:\n",
" pass\n",
"\n",
" return prices\n",
"\n",
"\n",
"\n",
"# 3. get_customer_orders\n",
"def get_customer_orders(inventory):\n",
" # First ask for number of orders\n",
" while True:\n",
" try:\n",
" num_orders = input(\"How many orders does the customer want to place? \")\n",
" num_orders = int(num_orders)\n",
" if num_orders < 0:\n",
" raise ValueError(\"Number of orders cannot be negative.\")\n",
" except ValueError as error:\n",
" print(f\"❌ Error: {error}. Please enter a valid integer.\")\n",
" else:\n",
" break\n",
" finally:\n",
" pass\n",
"\n",
" orders = []\n",
"\n",
" for i in range(num_orders):\n",
" while True:\n",
" try:\n",
" product = input(f\"Enter product name for order {i+1}: \").strip().lower()\n",
"\n",
" # Validate product name\n",
" if product not in inventory:\n",
" raise KeyError(f\"'{product}' is not in inventory.\")\n",
"\n",
" # Validate stock\n",
" if inventory[product] == 0:\n",
" raise ValueError(f\"'{product}' is out of stock.\")\n",
"\n",
" except KeyError as key_error:\n",
" print(f\"❌ Error: {key_error}. Please enter a valid product name.\")\n",
" except ValueError as value_error:\n",
" print(f\"❌ Error: {value_error} Please choose another product.\")\n",
" else:\n",
" orders.append(product)\n",
" inventory[product] -= 1\n",
" break\n",
" finally:\n",
" pass\n",
"\n",
" return orders\n",
"\n",
"\n",
"\n",
"# 4. Main program to test everything\n",
"def main():\n",
" products = [\"apple\", \"banana\", \"orange\"]\n",
"\n",
" print(\"\\n--- Initialize Inventory ---\")\n",
" inventory = initialize_inventory(products)\n",
"\n",
" print(\"\\n--- Set Product Prices ---\")\n",
" prices = calculate_total_price(products)\n",
"\n",
" print(\"\\n--- Customer Orders ---\")\n",
" orders = get_customer_orders(inventory)\n",
"\n",
" print(\"\\nFinal Orders:\", orders)\n",
" print(\"Remaining Inventory:\", inventory)\n",
" print(\"Prices:\", prices)\n",
"\n",
"\n",
"# Run program\n",
"# main()\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "e909c1d3-bc90-4950-99e6-0b13bab816e6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"--- Initialize Inventory ---\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity of apples available: 15\n",
"Enter the quantity of bananas available: 10\n",
"Enter the quantity of oranges available: 8\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"--- Set Product Prices ---\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the price for apple: 150\n",
"Enter the price for banana: 100\n",
"Enter the price for orange: 200\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"--- Customer Orders ---\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"How many orders does the customer want to place? apple\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"❌ Error: invalid literal for int() with base 10: 'apple'. Please enter a valid integer.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"How many orders does the customer want to place? 10\n",
"Enter product name for order 1: apple\n",
"Enter product name for order 2: banana\n",
"Enter product name for order 3: orange\n",
"Enter product name for order 4: orange\n",
"Enter product name for order 5: banana\n",
"Enter product name for order 6: apple\n",
"Enter product name for order 7: orange\n",
"Enter product name for order 8: apple\n",
"Enter product name for order 9: banana\n",
"Enter product name for order 10: orange\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Final Orders: ['apple', 'banana', 'orange', 'orange', 'banana', 'apple', 'orange', 'apple', 'banana', 'orange']\n",
"Remaining Inventory: {'apple': 12, 'banana': 7, 'orange': 4}\n",
"Prices: {'apple': 150.0, 'banana': 100.0, 'orange': 200.0}\n"
]
}
],
"source": [
"main()\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c10d7370-8f04-4303-a43c-50aab34170ba",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading