Skip to content
Open
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
376 changes: 373 additions & 3 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,383 @@
"metadata": {},
"outputs": [],
"source": [
"# your code goes here"
"#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",
"#we define the list of products\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"#we create the function, returning the inventory\n",
"def initialize_inventory (product_list):\n",
"\n",
" inventory_function={}\n",
" for product in product_list: #we use the for loop to fill the keys with product and the values with the input\n",
" inventory_function[product] = int(input(f\"¿How many {product} are there?\"))\n",
"\n",
" #print (inventory_function)\n",
" return (inventory_function)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9f27c36c",
"metadata": {},
"outputs": [],
"source": [
"# Updated function 1.\n",
"def initialize_inventory(product_list):\n",
" inventory_function = {}\n",
" for product in product_list:\n",
" while True:\n",
" try:\n",
" # Try to get user input and convert it to an integer\n",
" quantity = int(input(f\"How many {product} are there? \"))\n",
" if quantity < 0:\n",
" # Raise an error if the quantity is negative\n",
" raise ValueError(\"Quantity cannot be negative.\")\n",
" inventory_function[product] = quantity\n",
" except ValueError as e:\n",
" # Handle the ValueError if the input is not a valid integer or if the quantity is negative\n",
" print(f\"Invalid input: {e}. Please enter a valid number.\")\n",
" else:\n",
" # If no exceptions are raised, break the loop\n",
" break\n",
" finally:\n",
" # This block will always execute, indicating that the input for the current product has been processed\n",
" print(f\"Processed input for {product}.\")\n",
" return inventory_function\n",
"\n",
"# Example usage\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"inventory = initialize_inventory(products)\n",
"print(inventory)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dcbf9e01",
"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",
"\n",
"def get_customer_orders():\n",
"\n",
" yes_no=True\n",
" customer_orders_function=set()\n",
"\n",
" while yes_no==True: # Continue looping as long as yes_no is True\n",
" answer=input(f\"Do you want to order any product? Introduce Yes or No\").lower()\n",
" if answer==\"yes\":\n",
" product_name = input(\"Introduce the name of the product that you want to order: \").lower()\n",
" if product_name in products:\n",
" customer_orders_function.add(product_name)\n",
" else:\n",
" print(f\"Invalid product. You can choose between {products}\")\n",
" elif answer == \"no\":\n",
" print(\"Ok, no more products.\")\n",
" print (f\"The user wants to order these products: {customer_orders_function}\") \n",
" yes_no=False # Stop the loop when the user says \"no\"\n",
" break\n",
" else:\n",
" print(\"Non valida answer, please introduce yes or not\")\n",
" \n",
" return (customer_orders_function) # Return the set after exiting the loop"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9eec553f",
"metadata": {},
"outputs": [],
"source": [
"# Updated function 2.\n",
"def get_customer_orders():\n",
" yes_no = True\n",
" customer_orders_function = set()\n",
"\n",
" while yes_no: # Continue looping as long as yes_no is True\n",
" try:\n",
" answer = input(\"Do you want to order any product? Introduce Yes or No: \").lower()\n",
" if answer == \"yes\":\n",
" product_name = input(\"Introduce the name of the product that you want to order: \").lower()\n",
" if product_name in products:\n",
" customer_orders_function.add(product_name)\n",
" else:\n",
" raise ValueError(f\"Invalid product. You can choose between {products}\")\n",
" elif answer == \"no\":\n",
" print(\"Ok, no more products.\")\n",
" print(f\"The user wants to order these products: {customer_orders_function}\")\n",
" yes_no = False # Stop the loop when the user says \"no\"\n",
" else:\n",
" raise ValueError(\"Non valid answer, please introduce yes or no\")\n",
" except ValueError as e:\n",
" # Handle invalid product or invalid answer\n",
" print(f\"Error: {e}\")\n",
" finally:\n",
" # This block will always execute, indicating that the input for the current iteration has been processed\n",
" print(\"Processed input for this iteration.\")\n",
" \n",
" return customer_orders_function # Return the set after exiting the loop\n",
"\n",
"# Example usage\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"customer_orders = get_customer_orders()\n",
"print(customer_orders)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4fb517b4",
"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",
"\n",
" for product in customer_orders:\n",
" inventory[product]-=1"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d5e8a2d2",
"metadata": {},
"outputs": [],
"source": [
"# Updated 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 '{product}' not found in inventory.\")\n",
" if inventory[product] <= 0:\n",
" raise ValueError(f\"Product '{product}' is out of stock.\")\n",
" inventory[product] -= 1\n",
" except KeyError as e:\n",
" # Handle the case where the product is not found in the inventory\n",
" print(f\"Error: {e}\")\n",
" except ValueError as e:\n",
" # Handle the case where the product is out of stock\n",
" print(f\"Error: {e}\")\n",
" finally:\n",
" # This block will always execute, indicating that the update for the current product has been processed\n",
" print(f\"Processed update for {product}.\")\n",
" return inventory\n",
"\n",
"# Example usage\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"inventory = {\"t-shirt\": 10, \"mug\": 5, \"hat\": 2, \"book\": 0, \"keychain\": 1}\n",
"customer_orders = {\"t-shirt\", \"book\", \"keychain\"}\n",
"\n",
"updated_inventory = update_inventory(customer_orders, inventory)\n",
"print(updated_inventory)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4057e9ef",
"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",
" total_products_ordered=len(customer_orders)\n",
" percentage_products_ordered=len(customer_orders)/len(products)*100\n",
"\n",
" return (total_products_ordered, percentage_products_ordered)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4e725651",
"metadata": {},
"outputs": [],
"source": [
"# Updated function 4.\n",
"def calculate_order_statistics(customer_orders, products):\n",
" try:\n",
" # Calculate the total number of products ordered\n",
" total_products_ordered = len(customer_orders)\n",
" \n",
" # Calculate the percentage of unique products ordered\n",
" if len(products) == 0:\n",
" raise ValueError(\"The products list cannot be empty.\")\n",
" percentage_products_ordered = len(customer_orders) / len(products) * 100\n",
" \n",
" except ValueError as e:\n",
" # Handle the case where the products list is empty\n",
" print(f\"Error: {e}\")\n",
" return None, None\n",
" except Exception as e:\n",
" # Handle any other unexpected errors\n",
" print(f\"An unexpected error occurred: {e}\")\n",
" return None, None\n",
" else:\n",
" # If no exceptions are raised, return the calculated statistics\n",
" return total_products_ordered, percentage_products_ordered\n",
" finally:\n",
" # This block will always execute, indicating that the calculation has been processed\n",
" print(\"Processed order statistics calculation.\")\n",
"\n",
"# Example usage\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"customer_orders = {\"t-shirt\", \"book\", \"keychain\"}\n",
"\n",
"total_products_ordered, percentage_products_ordered = calculate_order_statistics(customer_orders, products)\n",
"print(f\"Total products ordered: {total_products_ordered}\")\n",
"print(f\"Percentage of unique products ordered: {percentage_products_ordered:.2f}%\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "464cb9de",
"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(f\"The total of unique products ordered: {order_statistics[0]} \\nThe percentage of unique products ordered: {order_statistics[1]}%\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "405e54a9",
"metadata": {},
"outputs": [],
"source": [
"# Updated function 5.\n",
"def print_order_statistics(order_statistics):\n",
" try:\n",
" # Check if order_statistics is a tuple with two elements\n",
" if not isinstance(order_statistics, tuple) or len(order_statistics) != 2:\n",
" raise ValueError(\"order_statistics must be a tuple with two elements.\")\n",
" \n",
" # Extract the total products ordered and the percentage of unique products ordered\n",
" total_products_ordered, percentage_products_ordered = order_statistics\n",
" \n",
" # Print the order statistics\n",
" print(f\"The total of unique products ordered: {total_products_ordered}\")\n",
" print(f\"The percentage of unique products ordered: {percentage_products_ordered:.2f}%\")\n",
" \n",
" except ValueError as e:\n",
" # Handle the case where order_statistics is not a valid tuple\n",
" print(f\"Error: {e}\")\n",
" except Exception as e:\n",
" # Handle any other unexpected errors\n",
" print(f\"An unexpected error occurred: {e}\")\n",
" finally:\n",
" # This block will always execute, indicating that the printing has been processed\n",
" print(\"Processed order statistics printing.\")\n",
"\n",
"# Example usage\n",
"order_statistics = (3, 60.0)\n",
"print_order_statistics(order_statistics)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "482ef10f",
"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 (\"Updated inventory:\")\n",
" for product in inventory:\n",
" print(f\"{product} {inventory[product]}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "020bb45f",
"metadata": {},
"outputs": [],
"source": [
"# Updated function 6.\n",
"def print_updated_inventory(inventory):\n",
" try:\n",
" # Check if inventory is a dictionary\n",
" if not isinstance(inventory, dict):\n",
" raise ValueError(\"inventory must be a dictionary.\")\n",
" \n",
" # Print the updated inventory\n",
" print(\"Updated inventory:\")\n",
" for product, quantity in inventory.items():\n",
" print(f\"{product}: {quantity}\")\n",
" \n",
" except ValueError as e:\n",
" # Handle the case where inventory is not a valid dictionary\n",
" print(f\"Error: {e}\")\n",
" except Exception as e:\n",
" # Handle any other unexpected errors\n",
" print(f\"An unexpected error occurred: {e}\")\n",
" finally:\n",
" # This block will always execute, indicating that the printing has been processed\n",
" print(\"Processed updated inventory printing.\")\n",
"\n",
"# Example usage\n",
"inventory = {\"t-shirt\": 9, \"mug\": 5, \"hat\": 2, \"book\": 0, \"keychain\": 0}\n",
"print_updated_inventory(inventory)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "337797da",
"metadata": {},
"outputs": [],
"source": [
"#7. Call the functions in the appropriate sequence to execute the program and manage customer orders.\n",
"# Example usage\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"# Step 1: Initialize inventory\n",
"inventory = initialize_inventory(products)\n",
"\n",
"# Step 2: Get customer orders\n",
"customer_orders = get_customer_orders()\n",
"\n",
"# Step 3: Update inventory based on customer orders\n",
"updated_inventory = update_inventory(customer_orders, inventory)\n",
"\n",
"# Step 4: Calculate order statistics\n",
"order_statistics = calculate_order_statistics(customer_orders, products)\n",
"\n",
"# Step 5: Print order statistics\n",
"print_order_statistics(order_statistics)\n",
"\n",
"# Step 6: Print updated inventory\n",
"print_updated_inventory(updated_inventory)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
Expand All @@ -66,7 +436,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.12.6"
}
},
"nbformat": 4,
Expand Down