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
329 changes: 329 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,329 @@
{
"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": 3,
"id": "cc2c441d-9dcf-4817-b097-cf6cbe440846",
"metadata": {},
"outputs": [],
"source": [
"# your code goes here\n",
"# Function 1\n",
"def initialize_inventory (products):\n",
" inventory = {}\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" quantity =int(input(f\"Enter the quantity available for {product}: \"))\n",
"\n",
" if quantity < 0:\n",
" raise ValueError(\"Quantity cannot be negative!\")\n",
" \n",
" except ValueError as err:\n",
" print(f\"Invalid input: {err}\")\n",
" else:\n",
" inventory [product] = quantity\n",
" break\n",
"\n",
" finally:\n",
" print(\"Attempt to enter quantity completed.\")\n",
" \n",
" return inventory\n",
"\n",
"# Function 2\n",
"def get_customer_orders ():\n",
" customer_orders = set()\n",
" \n",
" while True:\n",
" try:\n",
" order=input(\"Enter the other product that customer wants: \")\n",
"\n",
" if order == \"\":\n",
" raise ValueError(\"Product name cannot be empty!\")\n",
" customer_orders.add(order)\n",
" another_product=input(\"Would you like to add another product?(Answer only Yes or No) \")\n",
"\n",
" if another_product not in [\"yes\", \"no\"]:\n",
" raise ValueError(\"Answer must be Yes or No!\")\n",
"\n",
" if another_product==\"No\" or another_product==\"no\":\n",
" break\n",
"\n",
" except ValueError as err:\n",
" print(f\"Error: {err}\")\n",
" \n",
" return customer_orders\n",
"\n",
"# Function 3\n",
"def update_inventory (customer_orders, inventory):\n",
" for product in customer_orders:\n",
" try:\n",
" if product not in inventory:\n",
" raise KeyError(f\"{product} is not in inventory!\")\n",
" \n",
" inventory[product] -=1 \n",
"\n",
" except KeyError as err:\n",
" print(f\"Error: {err}\")\n",
" \n",
"\n",
" except ValueError as err:\n",
" print(f\"Error: {err}\")\n",
"\n",
" finally:\n",
" print(f\"Processed product: {product}\")\n",
"\n",
" \n",
"\n",
"# Function 4\n",
"def calculate_order_statistics (customer_orders, products):\n",
" try:\n",
" total_products_ordered = len(customer_orders)\n",
"\n",
" if len(products) == 0:\n",
" raise ZeroDivisionError(\"Product list is empty!\")\n",
" \n",
" percentage_ordered = (total_products_ordered / len(products)) * 100\n",
"\n",
" except ZeroDivisionError as err:\n",
" print(f\"Error: {err}\")\n",
" return 0, 0\n",
" \n",
" else:\n",
" return total_products_ordered,percentage_ordered\n",
"\n",
"#Function 5\n",
"def print_order_statistics(order_statistics):\n",
" try:\n",
" total_products_ordered = order_statistics [0]\n",
" percentage_ordered = order_statistics [1]\n",
" \n",
" print(\"Order Statistics:\")\n",
" print(\"Total Products Ordered:\", total_products_ordered)\n",
" print(\"Percentage of Products Ordered:\", percentage_ordered, \"%\")\n",
"\n",
" except Exception as err:\n",
" print(f\"Error: {err}\")\n",
" \n",
"#Function 6\n",
"def print_updated_inventory (inventory):\n",
" try:\n",
" print(\"Updated inventory:\")\n",
" for product, quantity in inventory.items():\n",
" print(f\"{product}: {quantity}\")\n",
"\n",
" except Exception as err:\n",
" print(f\"Error: {err}\")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "f659b253-0dbb-4304-96f8-e124e6dfe77f",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity available for t-shirt: 5\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Attempt to enter quantity completed.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity available for mug: 5\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Attempt to enter quantity completed.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity available for hat: 88\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Attempt to enter quantity completed.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity available for book: 5\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Attempt to enter quantity completed.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity available for keychain: 0\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Attempt to enter quantity completed.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the other product that customer wants: hat\n",
"Would you like to add another product?(Answer only Yes or No) yes\n",
"Enter the other product that customer wants: mug\n",
"Would you like to add another product?(Answer only Yes or No) yes\n",
"Enter the other product that customer wants: mug\n",
"Would you like to add another product?(Answer only Yes or No) yes\n",
"Enter the other product that customer wants: mug\n",
"Would you like to add another product?(Answer only Yes or No) yes\n",
"Enter the other product that customer wants: mug\n",
"Would you like to add another product?(Answer only Yes or No) yes\n",
"Enter the other product that customer wants: mug\n",
"Would you like to add another product?(Answer only Yes or No) \n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Answer must be Yes or No!\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the other product that customer wants: 0\n",
"Would you like to add another product?(Answer only Yes or No) no\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: '0 is not in inventory!'\n",
"Processed product: 0\n",
"Processed product: mug\n",
"Processed product: hat\n",
"Order Statistics:\n",
"Total Products Ordered: 3\n",
"Percentage of Products Ordered: 60.0 %\n",
"Updated inventory:\n",
"t-shirt: 5\n",
"mug: 4\n",
"hat: 87\n",
"book: 5\n",
"keychain: 0\n"
]
}
],
"source": [
"# List of products\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"inventory =initialize_inventory(products)\n",
"customer_orders = get_customer_orders ()\n",
"update_inventory (customer_orders, inventory)\n",
"order_statistics = calculate_order_statistics (customer_orders, products)\n",
"print_order_statistics(order_statistics)\n",
"print_updated_inventory (inventory)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "13fab9aa-79e1-4e47-86ff-fa2760f314c4",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:base] *",
"language": "python",
"name": "conda-base-py"
},
"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.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading