Skip to content

solved #28

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 1 commit 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
74 changes: 74 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
{
"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": null,
"id": "cc2c441d-9dcf-4817-b097-cf6cbe440846",
"metadata": {},
"outputs": [],
"source": [
"# your code goes here"
]
}
],
"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.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
245 changes: 243 additions & 2 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,248 @@
"metadata": {},
"outputs": [],
"source": [
"# your code goes here"
"# Initialize the dictionary for customer orders\n",
"customer_orders = {}\n",
"\n",
"# List of available products\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"def initialize_inventory(products):\n",
" # Initialize inventory as an empty dictionary\n",
" inventory = {}\n",
" # Input quantities for inventory\n",
" for product in products:\n",
" quantity = int(input(f\"Enter the quantity for {product}: \"))\n",
" inventory[product] = quantity # Set the quantity for each product\n",
" return inventory\n",
"\n",
"def get_customer_orders():\n",
" # Return the customer orders\n",
" return customer_orders\n",
"\n",
"def update_inventory(customer_orders, inventory):\n",
" # Update the inventory based on customer orders\n",
" for product, quantity in customer_orders.items():\n",
" if product in inventory:\n",
" inventory[product] -= quantity # Subtract the ordered quantity from inventory\n",
"\n",
"def calculate_order_statistics(customer_orders, products):\n",
" # Calculate total products ordered\n",
" total_ordered = sum(customer_orders.values())\n",
" \n",
" # Calculate the number of unique products ordered\n",
" unique_products_ordered = len(customer_orders)\n",
" \n",
" # Calculate the percentage of unique products ordered\n",
" percentage_unique = (unique_products_ordered / len(products)) * 100 if products else 0\n",
" \n",
" return total_ordered, percentage_unique\n",
"\n",
"def print_order_statistics(order_statistics):\n",
" # Return the order statistics in a list\n",
" return list(order_statistics)\n",
"\n",
"def print_updated_inventory(inventory):\n",
" # Print the updated inventory\n",
" print(\"Updated Inventory:\")\n",
" for product, quantity in inventory.items():\n",
" print(f\"{product}: {quantity}\")\n",
"\n",
"# Call the function to initialize inventory\n",
"inventory = initialize_inventory(products)\n",
"\n",
"print(\"Inventory:\", inventory)\n",
"\n",
"while True:\n",
" # a. Prompt the user to enter the name of a product\n",
" product = input(\"Enter the name of a product you want to order (t-shirt, mug, hat, book, keychain): \").strip().lower()\n",
" \n",
" # Check if the product is valid\n",
" if product in products:\n",
" # Ask for the quantity of the product\n",
" quantity = int(input(f\"Enter the quantity for {product}: \"))\n",
" \n",
" # Check if there is enough inventory for the order\n",
" if quantity <= inventory[product]:\n",
" # b. Add the product and quantity to the \"customer_orders\" dictionary\n",
" if product in customer_orders:\n",
" customer_orders[product] += quantity # Update quantity if product already exists\n",
" else:\n",
" customer_orders[product] = quantity # Add new product with quantity\n",
" \n",
" # Update the inventory\n",
" inventory[product] -= quantity\n",
" print(f\"{quantity} of {product} has been added to your orders.\")\n",
" else:\n",
" print(f\"Sorry, there is not enough inventory for {product}. Available quantity: {inventory[product]}\")\n",
" else:\n",
" print(\"Invalid product. Please choose from the available products.\")\n",
" \n",
" # c. Ask the user if they want to add another product\n",
" another = input(\"Do you want to add another product? (yes/no): \").strip().lower()\n",
" \n",
" # d. Continue the loop until the user does not want to add another product\n",
" if another != 'yes':\n",
" break\n",
"\n",
"# Update the inventory based on customer orders\n",
"update_inventory(customer_orders, inventory)\n",
"\n",
"# Display the final orders and remaining inventory\n",
"print(\"Your final orders are:\", get_customer_orders())\n",
"print(\"Remaining inventory:\", inventory)\n",
"\n",
"# Print the updated inventory\n",
"print_updated_inventory(inventory)\n",
"\n",
"# Calculate and display order statistics\n",
"total_ordered, percentage_unique = calculate_order_statistics(customer_orders, products)\n",
"print(f\"Total products ordered: {total_ordered}\")\n",
"print(f\"Percentage of unique products ordered: {percentage_unique:.2f}%\")\n",
"\n",
"# Get order statistics in a list\n",
"order_statistics_list = print_order_statistics((total_ordered, percentage_unique))\n",
"print(\"Order statistics in list format:\", order_statistics_list)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "42d755d7-6a9b-44da-adb3-c1d36d3ca53c",
"metadata": {},
"outputs": [],
"source": [
"# Initialize the dictionary for customer orders\n",
"customer_orders = {}\n",
"\n",
"# List of available products\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"def initialize_inventory(products):\n",
" \"\"\"\n",
" Initialize inventory with quantities based on user input.\n",
" \"\"\"\n",
" inventory = {}\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" # Input quantities for inventory\n",
" quantity = int(input(f\"Enter the quantity for {product}: \"))\n",
" if quantity < 0:\n",
" raise ValueError(\"Quantity cannot be negative. Please enter a valid number.\")\n",
" inventory[product] = quantity\n",
" break\n",
" except ValueError as e:\n",
" print(f\"Invalid input: {e}. Please try again.\")\n",
" return inventory\n",
"\n",
"def get_customer_orders():\n",
" \"\"\"\n",
" Return the customer orders.\n",
" \"\"\"\n",
" return customer_orders\n",
"\n",
"def update_inventory(customer_orders, inventory):\n",
" \"\"\"\n",
" Update the inventory based on customer orders.\n",
" \"\"\"\n",
" for product, quantity in customer_orders.items():\n",
" if product in inventory:\n",
" inventory[product] -= quantity # Subtract the ordered quantity from inventory\n",
" else:\n",
" print(f\"Warning: Product '{product}' not found in inventory. Skipping.\")\n",
"\n",
"def calculate_order_statistics(customer_orders, products):\n",
" \"\"\"\n",
" Calculate statistics about the customer's order.\n",
" \"\"\"\n",
" try:\n",
" total_ordered = sum(customer_orders.values())\n",
" unique_products_ordered = len(customer_orders)\n",
" percentage_unique = (unique_products_ordered / len(products)) * 100 if products else 0\n",
" return total_ordered, percentage_unique\n",
" except ZeroDivisionError:\n",
" print(\"Error: No products available for calculation.\")\n",
" return 0, 0\n",
"\n",
"def print_order_statistics(order_statistics):\n",
" \"\"\"\n",
" Return the order statistics in a list.\n",
" \"\"\"\n",
" return list(order_statistics)\n",
"\n",
"def print_updated_inventory(inventory):\n",
" \"\"\"\n",
" Print the updated inventory.\n",
" \"\"\"\n",
" print(\"Updated Inventory:\")\n",
" for product, quantity in inventory.items():\n",
" print(f\"{product}: {quantity}\")\n",
"\n",
"# Call the function to initialize inventory\n",
"inventory = initialize_inventory(products)\n",
"\n",
"print(\"Inventory:\", inventory)\n",
"\n",
"while True:\n",
" # a. Prompt the user to enter the name of a product\n",
" product = input(\"Enter the name of a product you want to order (t-shirt, mug, hat, book, keychain): \").strip().lower()\n",
" \n",
" # Check if the product is valid\n",
" if product in products:\n",
" while True:\n",
" try:\n",
" # Ask for the quantity of the product\n",
" quantity = int(input(f\"Enter the quantity for {product}: \"))\n",
" if quantity <= 0:\n",
" raise ValueError(\"Quantity must be a positive integer.\")\n",
" \n",
" # Check if there is enough inventory for the order\n",
" if quantity <= inventory[product]:\n",
" # b. Add the product and quantity to the \"customer_orders\" dictionary\n",
" if product in customer_orders:\n",
" customer_orders[product] += quantity # Update quantity if product already exists\n",
" else:\n",
" customer_orders[product] = quantity # Add new product with quantity\n",
" \n",
" # Update the inventory\n",
" inventory[product] -= quantity\n",
" print(f\"{quantity} of {product} has been added to your orders.\")\n",
" break\n",
" else:\n",
" print(f\"Sorry, there is not enough inventory for {product}. Available quantity: {inventory[product]}\")\n",
" break\n",
" except ValueError as e:\n",
" print(f\"Invalid input: {e}. Please enter a valid quantity.\")\n",
" else:\n",
" print(\"Invalid product. Please choose from the available products.\")\n",
" \n",
" # c. Ask the user if they want to add another product\n",
" another = input(\"Do you want to add another product? (yes/no): \").strip().lower()\n",
" \n",
" # d. Continue the loop until the user does not want to add another product\n",
" if another != 'yes':\n",
" break\n",
"\n",
"# Update the inventory based on customer orders\n",
"update_inventory(customer_orders, inventory)\n",
"\n",
"# Display the final orders and remaining inventory\n",
"print(\"Your final orders are:\", get_customer_orders())\n",
"print(\"Remaining inventory:\", inventory)\n",
"\n",
"# Print the updated inventory\n",
"print_updated_inventory(inventory)\n",
"\n",
"# Calculate and display order statistics\n",
"total_ordered, percentage_unique = calculate_order_statistics(customer_orders, products)\n",
"if total_ordered and percentage_unique:\n",
" print(f\"Total products ordered: {total_ordered}\")\n",
" print(f\"Percentage of unique products ordered: {percentage_unique:.2f}%\")\n",
"\n",
"# Get order statistics in a list\n",
"order_statistics_list = print_order_statistics((total_ordered, percentage_unique))\n",
"print(\"Order statistics in list format:\", order_statistics_list)"
]
}
],
Expand All @@ -66,7 +307,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.12.4"
}
},
"nbformat": 4,
Expand Down