Skip to content

lab done #451

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: main
Choose a base branch
from
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
276 changes: 276 additions & 0 deletions lab_error_handling_end.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e",
"metadata": {},
"source": [
"# Lab | Error Handling"
]
},
{
"cell_type": "markdown",
"id": "bc99b386-7508-47a0-bcdb-d969deaf6c8b",
"metadata": {},
"source": [
"## Exercise: Error Handling for Managing Customer Orders\n",
"\n",
"The implementation of your code for managing customer orders assumes that the user will always enter a valid input. \n",
"\n",
"For example, we could modify the `initialize_inventory` function to include error handling.\n",
" - If the user enters an invalid quantity (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter the quantity for that product.\n",
" - Use a try-except block to handle the error and continue prompting the user until a valid quantity is entered.\n",
"\n",
"```python\n",
"# Step 1: Define the function for initializing the inventory with error handling\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\n",
"\n",
"# Or, in another way:\n",
"\n",
"def initialize_inventory(products):\n",
" inventory = {}\n",
" for product in products:\n",
" valid_input = False\n",
" while not valid_input:\n",
" try:\n",
" quantity = int(input(f\"Enter the quantity of {product}s available: \"))\n",
" if quantity >= 0:\n",
" inventory[product] = quantity\n",
" valid_input = True\n",
" else:\n",
" print(\"Quantity cannot be negative. Please enter a valid quantity.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid quantity.\")\n",
" return inventory\n",
"```\n",
"\n",
"Let's enhance your code by implementing error handling to handle invalid inputs.\n",
"\n",
"Follow the steps below to complete the exercise:\n",
"\n",
"2. Modify the `calculate_total_price` function to include error handling.\n",
" - If the user enters an invalid price (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter the price for that product.\n",
" - Use a try-except block to handle the error and continue prompting the user until a valid price is entered.\n",
"\n",
"3. Modify the `get_customer_orders` function to include error handling.\n",
" - If the user enters an invalid number of orders (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter the number of orders.\n",
" - If the user enters an invalid product name (e.g., a product name that is not in the inventory), or that doesn't have stock available, display an error message and ask them to re-enter the product name. *Hint: you will need to pass inventory as a parameter*\n",
" - Use a try-except block to handle the error and continue prompting the user until a valid product name is entered.\n",
"\n",
"4. Test your code by running the program and deliberately entering invalid quantities and product names. Make sure the error handling mechanism works as expected.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6086e47e",
"metadata": {},
"outputs": [],
"source": [
"products = ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "cd20bcf1",
"metadata": {},
"outputs": [],
"source": [
"#1\n",
"def initialize_inventory(products):\n",
" \"\"\"\n",
" Initializes the inventory dict with products names as keys\n",
" and quantities as values.\n",
"\n",
" returns: dict --> initialized inventory\n",
" \"\"\"\n",
" inventory = {}\n",
" for product in products:\n",
" valid_input = False\n",
" while not valid_input:\n",
" try:\n",
" product_qt = int(input(f'Enter product quantity for {product}:'))\n",
" if product_qt >= 0:\n",
" inventory[product] = product_qt\n",
" valid_input = True\n",
" else:\n",
" print('quantity must be positive number')\n",
" except ValueError:\n",
" print('Invalid input, enter nr.')\n",
" return inventory\n",
"\n",
"#2\n",
"def get_customer_orders():\n",
" \"\"\"\n",
" Prompt user to input product names for customer orders\n",
" and returns them as a set.\n",
"\n",
" returns: unique orderes product names\n",
" \"\"\"\n",
" nr_orders = 0\n",
" while True:\n",
" try:\n",
" nr_orders = int(input('Enter how many products to order: ').strip())\n",
" if nr_orders > 0:\n",
" break\n",
" else:\n",
" print('Enter non negative nr.')\n",
" except ValueError:\n",
" print('Error. Enter whole number.')\n",
"\n",
" customer_orders = set()\n",
" if nr_orders == 0:\n",
" print('Customer wants to order 0 products.')\n",
" return customer_orders\n",
" print(f'Enter {nr_orders} products name:')\n",
"\n",
" while len(customer_orders) < nr_orders:\n",
" valid_product_slot = False\n",
" while not valid_product_slot:\n",
" order_input = input(f'Enter product name #{len(customer_orders) + 1}: ').strip()\n",
" if order_input.lower() == 'done':\n",
" if not customer_orders and nr_orders > 0:\n",
" print('No product choose. Exiting order')\n",
" else:\n",
" print('Finishing order input.')\n",
" return customer_orders\n",
" if not order_input:\n",
" print(\"Error. Please enter product name or 'done'\")\n",
" continue\n",
"\n",
" if order_input in inventory:\n",
" if inventory[order_input] > 0:\n",
" if order_input not in customer_orders:\n",
" customer_orders.add(order_input)\n",
" valid_product_slot = True\n",
" else:\n",
" print(f'{order_input} already added to order')\n",
" else:\n",
" print(f'Error: {order_input} out of stock. Choose another.')\n",
" else:\n",
" print(f'Error: {order_input}not found.')\n",
" \n",
" return customer_orders\n",
"\n",
"\n",
"#3\n",
"def update_inventory(customer_orders, inventory):\n",
" \"\"\"\n",
" Updates inventory dict based on customer orders.\n",
" Reduces prodect quantity for each ordered product if available\n",
"\n",
" returns: None\n",
" \"\"\"\n",
" for order_item in customer_orders:\n",
" if order_item in inventory:\n",
" if inventory[order_item] > 0:\n",
" inventory[order_item] -= 1\n",
" print(f\"{order_item}. New quantity: {inventory[order_item]}\")\n",
" else:\n",
" print(f\"'{order_item}' is out of stock.\")\n",
" else:\n",
" print(f\"'{order_item}' not found in inventory.\")\n",
"\n",
"#4\n",
"def calculate_order_statistics(customer_orders, products):\n",
" \"\"\"\n",
" Calculates statistics based on customer orders\n",
" - Total nr. of unique products ordered\n",
" - Percentage of unique products ordered compared to available products\n",
" \n",
" returns: tuple (total_ordered, percentage_ordered)\n",
" \"\"\"\n",
" total_ordered = len(customer_orders)\n",
" total_available = len(products)\n",
" percentage_ordered = (total_ordered / total_available) * 100\n",
"\n",
" return (total_ordered, percentage_ordered)\n",
"\n",
"#5\n",
"def print_order_statistics(order_statistics):\n",
" \"\"\"\n",
" Prints the statistics calculated\n",
" \"\"\"\n",
" total_ordered, percentage_ordered = order_statistics\n",
" print('Order Statistics:')\n",
" print(f'Total Products Ordered: {total_ordered}')\n",
" print(f'Percentage of Products Ordered: {percentage_ordered:.2f}%')\n",
"\n",
"#6\n",
"def print_updated_inventory(inventory):\n",
" if inventory:\n",
" for product, quantity in inventory.items():\n",
" print(f'{product}: {quantity}')\n",
" else:\n",
" print('Inventory is empty.')\n",
" \n",
"def total_price_order(customer_orders):\n",
" \"\"\"\n",
" Calculates de total price of the order. Prompts user to enter price\n",
" of each product and summs the them.\n",
" Assume 1 unit of each\n",
"\n",
" returns: total price of order --> float\n",
" \"\"\"\n",
" product_prices = []\n",
" if customer_orders:\n",
" for product in customer_orders:\n",
" valid_price = False\n",
" while not valid_price:\n",
" try:\n",
" price = float(input(f'Enter price for {product}: €'))\n",
" if price >= 0:\n",
" product_prices.append(price)\n",
" valid_price = True\n",
" else:\n",
" print('Invalid. Price must be positive.')\n",
" except ValueError:\n",
" print('Invalid. Enter price must be numerical.')\n",
" else:\n",
" print('No product to price')\n",
" \n",
" total_price = sum(price for price in product_prices)\n",
" print(f'Total price: {total_price}')\n",
"\n",
" return total_price\n",
"\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.13.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}