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
386 changes: 386 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,386 @@
{
"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": 47,
"id": "cc2c441d-9dcf-4817-b097-cf6cbe440846",
"metadata": {},
"outputs": [],
"source": [
"def main():\n",
" products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
" inventory = initialize_inventory(products)\n",
" customer_orders = get_customer_orders(inventory)\n",
" inventory = 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": 48,
"id": "1933703b",
"metadata": {},
"outputs": [],
"source": [
"def initialize_inventory(products):\n",
" inventory = {}\n",
" for product in products:\n",
" valid_input = False\n",
" while not valid_input:\n",
" try:\n",
" qty = input(f\"Please provide number of {product} available: \")\n",
" if not qty.isnumeric() or int(qty) < 0:\n",
" raise ValueError(\"Invalid input. Please enter a non-negative number.\") \n",
" except ValueError as v:\n",
" print(v)\n",
" else:\n",
" inventory[product] = int(qty)\n",
" valid_input = True\n",
" finally:\n",
" print(f\"Currently, these are the products in the inventory: {inventory}\")\n",
" return inventory"
]
},
{
"cell_type": "code",
"execution_count": 49,
"id": "f81c9580",
"metadata": {},
"outputs": [],
"source": [
"def get_customer_orders(inventory):\n",
" valid_input = False\n",
" while not valid_input:\n",
" try:\n",
" qty = int((input(\"Enter the number of customer orders: \")))\n",
" if qty > 0:\n",
" valid_input = True\n",
" else:\n",
" print(\"Number of customer orders cannot be zero or negative. Please enter a valid price.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a number of customer orders\")\n",
" customer_orders = set()\n",
" for i in range(qty):\n",
" valid_input = False\n",
" while not valid_input:\n",
" try:\n",
" order = input(\"Enter the name of a product that a customer wants to order:\").lower()\n",
" if order not in [word.lower() for word in inventory.keys()]:\n",
" raise TypeError(f\"The product is not in the inventory. Products available are: {[product for product in inventory.keys()]}\")\n",
" elif inventory[order] <= 0:\n",
" raise ValueError(f\"The product is not in stock! Our current stock is: {inventory}\")\n",
" except (TypeError, ValueError) as e:\n",
" print(e)\n",
" else:\n",
" customer_orders.add(order)\n",
" valid_input = True\n",
" return customer_orders"
]
},
{
"cell_type": "code",
"execution_count": 50,
"id": "d30e75c9",
"metadata": {},
"outputs": [],
"source": [
"def update_inventory(customer_orders, inventory):\n",
" for product in customer_orders:\n",
" try:\n",
" inventory[product] -= 1\n",
" except KeyError as k:\n",
" print(\"At least one of the products in the customer order is no in the inventory\")\n",
" return inventory"
]
},
{
"cell_type": "code",
"execution_count": 51,
"id": "741c83b5",
"metadata": {},
"outputs": [],
"source": [
"def calculate_order_statistics(customer_orders, products):\n",
" total_products_ordered = len(customer_orders)\n",
" try:\n",
" perc = (total_products_ordered / len(products)) * 100\n",
" except ZeroDivisionError:\n",
" print(\"Product list is empty.\")\n",
" perc = 0\n",
" order_statistics = [total_products_ordered, int(perc)]\n",
" return order_statistics"
]
},
{
"cell_type": "code",
"execution_count": 52,
"id": "b7e0e106",
"metadata": {},
"outputs": [],
"source": [
"def print_order_statistics(order_statistics):\n",
" print(f\"The total number of products ordered is {order_statistics[0]}, and the percentage of unique products ordered is {order_statistics[1]}%\")"
]
},
{
"cell_type": "code",
"execution_count": 53,
"id": "f109be01",
"metadata": {},
"outputs": [],
"source": [
"def print_updated_inventory(inventory):\n",
" print(f\"The updated inventory is: {inventory}\")"
]
},
{
"cell_type": "code",
"execution_count": 54,
"id": "99d37db8-caec-43fc-b34e-fd9ecf57d78d",
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Please provide number of t-shirt available: no\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input. Please enter a non-negative number.\n",
"Currently, these are the products in the inventory: {}\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Please provide number of t-shirt available: -2\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input. Please enter a non-negative number.\n",
"Currently, these are the products in the inventory: {}\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Please provide number of t-shirt available: 3\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Currently, these are the products in the inventory: {'t-shirt': 3}\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Please provide number of mug available: 0\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Currently, these are the products in the inventory: {'t-shirt': 3, 'mug': 0}\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Please provide number of hat available: 2\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Currently, these are the products in the inventory: {'t-shirt': 3, 'mug': 0, 'hat': 2}\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Please provide number of book available: 34\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Currently, these are the products in the inventory: {'t-shirt': 3, 'mug': 0, 'hat': 2, 'book': 34}\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Please provide number of keychain available: 1\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Currently, these are the products in the inventory: {'t-shirt': 3, 'mug': 0, 'hat': 2, 'book': 34, 'keychain': 1}\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the number of customer orders: none\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input. Please enter a number of customer orders\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the number of customer orders: 0\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of customer orders cannot be zero or negative. Please enter a valid price.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the number of customer orders: -2\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of customer orders cannot be zero or negative. Please enter a valid price.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the number of customer orders: 3\n",
"Enter the name of a product that a customer wants to order: mug\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"The product is not in stock! Our current stock is: {'t-shirt': 3, 'mug': 0, 'hat': 2, 'book': 34, 'keychain': 1}\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the name of a product that a customer wants to order: hat\n",
"Enter the name of a product that a customer wants to order: book\n",
"Enter the name of a product that a customer wants to order: keychain\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"The total number of products ordered is 3, and the percentage of unique products ordered is 60%\n",
"The updated inventory is: {'t-shirt': 3, 'mug': 0, 'hat': 1, 'book': 33, 'keychain': 0}\n"
]
}
],
"source": [
"main()"
]
}
],
"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.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading