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
Binary file added .DS_Store
Binary file not shown.
322 changes: 322 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,322 @@
{
"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": 3,
"id": "c410c1b4-888d-4760-9550-d4e5313283aa",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"========== Please indicate the stock and what do you want to order ==========\n",
"Products: t-shirt, mug, hat, book, keychain\n",
"==============================================\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity of t-shirts available: 4\n",
"Enter the quantity of mugs available: 6\n",
"Enter the quantity of hats available: 3\n",
"Enter the quantity of books available: 2\n",
"Enter the quantity of keychains available: 1\n",
"How many products do you want to order? 4\n",
"Enter a product: fhghg\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid product. Please choose from: t-shirt, mug, hat, book, keychain\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter a product: book\n",
"Enter a product: hat\n",
"Enter a product: hhgjf\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid product. Please choose from: t-shirt, mug, hat, book, keychain\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter a product: keychain\n",
"Enter a product: hat\n",
"Enter the price of the keychain in EUR: 4\n",
"Enter the price of the hat in EUR: 5\n",
"Enter the price of the book in EUR: 6\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Order Statistics:\n",
"======================\n",
"Total Products Ordered: 4\n",
"Percentage of Products Ordered: 60.0%\n",
"Updated Inventory:\n",
"t-shirt: 4\n",
"mug: 6\n",
"hat: 1\n",
"book: 1\n",
"Total order price: €15.00\n"
]
}
],
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"\n",
"def initialize_inventory(products):\n",
" inventory = {}\n",
"\n",
" for product in products:\n",
" while True:\n",
" value = input(f\"Enter the quantity of {product}s available: \")\n",
"\n",
" if value.isdigit() and int(value) >= 0:\n",
" inventory[product] = int(value)\n",
" break\n",
" else:\n",
" print(\"Please enter a valid positive number.\")\n",
"\n",
" return inventory\n",
"\n",
"\n",
"def get_customer_orders(inventory):\n",
" user_product_number = input(\"How many products do you want to order? \")\n",
"\n",
" if user_product_number.isdigit() and int(user_product_number) > 0:\n",
" user_product_number = int(user_product_number)\n",
"\n",
" orders = []\n",
"\n",
" for n in range(user_product_number):\n",
"\n",
" while True:\n",
" product = input(\"Enter a product: \").strip().lower()\n",
"\n",
" if product not in inventory:\n",
" print(\"Invalid product. Please choose from:\", \", \".join(inventory.keys()))\n",
" elif inventory[product] <= 0:\n",
" print(\"Product out of stock.\")\n",
" else:\n",
" orders.append(product)\n",
" break\n",
"\n",
" return {\n",
" product: orders.count(product)\n",
" for product in set(orders)\n",
" }\n",
"\n",
" else:\n",
" print(\"Please enter a positive whole number.\")\n",
" return {}\n",
"\n",
"\n",
"def calculate_order_statistics(customer_orders, products):\n",
" total_ordered = sum(customer_orders.values())\n",
" percentage_ordered = (len(customer_orders) / len(products)) * 100\n",
" return total_ordered, percentage_ordered\n",
"\n",
"\n",
"def print_order_statistics(order_statistics):\n",
" total, percentage = order_statistics\n",
"\n",
" print(\"Order Statistics:\")\n",
" print(\"======================\")\n",
" print(f\"Total Products Ordered: {total}\")\n",
" print(f\"Percentage of Products Ordered: {percentage}%\")\n",
"\n",
"\n",
"def update_inventory(customer_orders, inventory):\n",
"\n",
" updated_inventory = {\n",
" product: inventory[product] - customer_orders.get(product, 0)\n",
" for product in inventory\n",
" }\n",
"\n",
" return {\n",
" product: qty\n",
" for product, qty in updated_inventory.items()\n",
" if qty > 0\n",
" }\n",
"\n",
"\n",
"def print_updated_inventory(inventory):\n",
" print(\"Updated Inventory:\")\n",
" for product, qty in inventory.items():\n",
" print(f\"{product}: {qty}\")\n",
"\n",
"\n",
"def total_order_price(customer_orders):\n",
"\n",
" product_price = {}\n",
"\n",
" for product in customer_orders:\n",
"\n",
" while True:\n",
" try:\n",
" price = float(input(f\"Enter the price of the {product} in EUR: \"))\n",
"\n",
" if price < 0:\n",
" raise ValueError\n",
"\n",
" product_price[product] = price\n",
" break\n",
"\n",
" except ValueError:\n",
" print(\"Please enter a valid price.\")\n",
"\n",
" return sum(product_price.values())\n",
"\n",
"\n",
"def print_total_price(order_price):\n",
" print(f\"Total order price: €{order_price:.2f}\")\n",
"\n",
"\n",
"# -------------------------------------------------------------------------------------------\n",
"\n",
"print(\"========== Please indicate the stock and what do you want to order ==========\")\n",
"print(\"Products: t-shirt, mug, hat, book, keychain\")\n",
"print(\"==============================================\")\n",
"\n",
"inventory = initialize_inventory(products)\n",
"\n",
"customer_orders = get_customer_orders(inventory)\n",
"\n",
"inventory = update_inventory(customer_orders, inventory)\n",
"\n",
"order_statistics = calculate_order_statistics(customer_orders, products)\n",
"\n",
"order_price = total_order_price(customer_orders)\n",
"\n",
"print()\n",
"print_order_statistics(order_statistics)\n",
"\n",
"print_updated_inventory(inventory)\n",
"\n",
"print_total_price(order_price)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3c31d5c0-74a0-49bc-86ef-690d3108c46b",
"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.13.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading