Skip to content

Solved lab #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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
300 changes: 300 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,300 @@
{
"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": 39,
"id": "cc2c441d-9dcf-4817-b097-cf6cbe440846",
"metadata": {},
"outputs": [],
"source": [
"#1. Define a function named initialize_inventory that takes products as a parameter. \n",
"#Inside the function, implement the code for initializing the inventory dictionary using a loop and user input.\n",
"\n",
"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(\"Invalid quantity! Please enter a non-negative value.\")\n",
" valid_quantity = True\n",
" except ValueError as error:\n",
" print(f\"Error: {error}\")\n",
" inventory[product] = quantity\n",
" return inventory"
]
},
{
"cell_type": "code",
"execution_count": 41,
"id": "3a147ada-e9af-4bb2-bc6f-f747ad3bcbf3",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter stock quantity for t-shirt: 6\n",
"Enter stock quantity for mug: 3\n",
"Enter stock quantity for hat: hj\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Please only input integers for the stock quantity\n"
]
}
],
"source": [
"inventory = initialize_inventory([\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"])"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "c2f8b133-c0fb-427e-a4c1-657de98eb318",
"metadata": {},
"outputs": [],
"source": [
"#2. Define a function named get_customer_orders that takes no parameters. \n",
"#Inside the function, implement the code for prompting the user to enter the product names using a loop. \n",
"# The function should return the customer_orders set.\n",
"def get_customer_orders():\n",
" try:\n",
" customer_orders = list()\n",
" again = \"y\"\n",
" products = list(inventory.keys())\n",
"\n",
" while again == \"y\":\n",
" product = input(f\"What product do you want to order from this list: {products} \").lower().strip()\n",
"\n",
" # Validate product selection\n",
" if product in inventory:\n",
" customer_orders.append(product)\n",
" else:\n",
" # Handle invalid product input\n",
" while product not in inventory:\n",
" product = input(f\"Please only select a product from this list: {products} \").lower().strip()\n",
" if not product:\n",
" print(\"You did not enter a valid product.\")\n",
" break\n",
" elif product in inventory:\n",
" customer_orders.append(product)\n",
" break\n",
"\n",
" # Ask if the user wants to order again\n",
" again = input(\"Would you like to place another order? (y/n): \").lower().strip()\n",
"\n",
" # Handle invalid 'again' input\n",
" while again not in [\"y\", \"n\"]:\n",
" print(\"Invalid input. Please enter 'y' or 'n'.\")\n",
" again = input(\"Would you like to place another order? (y/n): \").lower().strip()\n",
"\n",
" print(\"Thanks for ordering!\")\n",
" return customer_orders\n",
"\n",
" except ValueError as ve:\n",
" print(f\"Error: {ve}\")\n",
" except Exception as e:\n",
" print(f\"An unexpected error occurred: {e}\")\n"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "ca77e175-abea-45f5-bc39-eea2f810eb29",
"metadata": {},
"outputs": [],
"source": [
"#3. Define a function named update_inventory that takes customer_orders and inventory as parameters. \n",
"#Inside the function, implement the code for updating the inventory dictionary based on the customer orders.\n",
"\n",
"def update_inventory(customer_orders, inventory):\n",
" for order in customer_orders:\n",
" if order in inventory:\n",
" inventory[order] -= 1\n",
" if inventory[order] < 0:\n",
" raise ValueError(f\"{order} inventory is below 0. Please check and amend.\")\n",
" print(\"Updated inventory:\")\n",
" for key, value in inventory.items():\n",
" print(str(key) + \": \" + str(value))\n",
"\n",
" return inventory"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "1abbcf61-e0a7-4c19-a6cb-95e24228ff78",
"metadata": {},
"outputs": [],
"source": [
"#4. Define a function named calculate_order_statistics that takes customer_orders and products as parameters.\n",
"#Inside the function, implement the code for calculating the order statistics (total products ordered, and percentage of unique products ordered).\n",
"#The function should return these values.\n",
"\n",
"def calculate_order_statistics(customer_orders, products):\n",
" \n",
" customer_orders_set = set()\n",
" \n",
" for i in customer_orders:\n",
" customer_orders_set.add(i)\n",
" \n",
" num_ordered = len(customer_orders_set)\n",
" pct_ordered = 100 * len(customer_orders_set) / len(products) \n",
" order_statistics = num_ordered, pct_ordered\n",
" return order_statistics"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "098fc378-3510-42bf-96b0-bbd965785843",
"metadata": {},
"outputs": [],
"source": [
"#5. Define a function named print_order_statistics that takes order_statistics as a parameter.\n",
"#Inside the function, implement the code for printing the order statistics.\n",
"\n",
"def print_order_statistics(order_statistics):\n",
" print(\"Total unique products ordered: \" + str( order_statistics[0] )\n",
" print(\"Percentage of product range ordered: \" + str( order_statistics[1] ) + \"%\")"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "af36731f-d478-45e0-b4cf-56a3b78ee41a",
"metadata": {},
"outputs": [],
"source": [
"#6. Define a function named print_updated_inventory that takes inventory as a parameter.\n",
"#Inside the function, implement the code for printing the updated inventory.\n",
"\n",
"def print_updated_inventory(inventory):\n",
" print(inventory)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"id": "f43128fd-64ec-47df-b8a3-16c71f94ccd3",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter stock quantity for t-shirt: 0\n",
"Enter stock quantity for mug: 34\n",
"Enter stock quantity for hat: 7\n",
"Enter stock quantity for book: 2\n",
"Enter stock quantity for keychain: 7\n",
"What product do you want to order from this list:['t-shirt', 'mug', 'hat', 'book', 'keychain'] t-shirt\n",
"Would you like to place another order? (y/n): n\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Thanks for ordering\n"
]
},
{
"ename": "ValueError",
"evalue": "t-shirt inventory is below 0. Please check and amend.",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[45], line 3\u001b[0m\n\u001b[0;32m 1\u001b[0m inventory \u001b[38;5;241m=\u001b[39m initialize_inventory([\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mt-shirt\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmug\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mhat\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mbook\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mkeychain\u001b[39m\u001b[38;5;124m\"\u001b[39m])\n\u001b[0;32m 2\u001b[0m customer_orders \u001b[38;5;241m=\u001b[39m get_customer_orders()\n\u001b[1;32m----> 3\u001b[0m inventory \u001b[38;5;241m=\u001b[39m update_inventory(customer_orders, inventory)\n\u001b[0;32m 4\u001b[0m order_statistics \u001b[38;5;241m=\u001b[39m calculate_order_statistics(customer_orders, products)\n\u001b[0;32m 5\u001b[0m num_ordered, pct_ordered \u001b[38;5;241m=\u001b[39m order_statistics\n",
"Cell \u001b[1;32mIn[43], line 9\u001b[0m, in \u001b[0;36mupdate_inventory\u001b[1;34m(customer_orders, inventory)\u001b[0m\n\u001b[0;32m 7\u001b[0m inventory[order] \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m 8\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m inventory[order] \u001b[38;5;241m<\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[1;32m----> 9\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00morder\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m inventory is below 0. Please check and amend.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 10\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mUpdated inventory:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 11\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m key, value \u001b[38;5;129;01min\u001b[39;00m inventory\u001b[38;5;241m.\u001b[39mitems():\n",
"\u001b[1;31mValueError\u001b[0m: t-shirt inventory is below 0. Please check and amend."
]
}
],
"source": [
"inventory = initialize_inventory([\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"])\n",
"customer_orders = get_customer_orders()\n",
"inventory = update_inventory(customer_orders, inventory)\n",
"order_statistics = calculate_order_statistics(customer_orders, products)\n",
"num_ordered, pct_ordered = order_statistics\n",
"print_order_statistics(order_statistics)\n",
"print_updated_inventory(inventory)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6d961790-3b14-4a22-8694-137de6beedf9",
"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.12.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading