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
358 changes: 358 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,358 @@
{
"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": 1,
"id": "14a1fb09-2344-4c9e-9c99-09a05f34997c",
"metadata": {},
"outputs": [],
"source": [
"# 1. # Step 1: Define the function for initializing the inventory with error handling\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\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"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7379cf8a-7081-458b-801a-5d39e4b98092",
"metadata": {},
"outputs": [],
"source": [
"# 2. Modify the calculate_total_price function to include error handling\n",
"def calculate_total_price (customer_orders):\n",
" total_price = 0\n",
"\n",
" #loop for iterate on each product of the order\n",
" for product in customer_orders :\n",
" valid_price = False\n",
" while not valid_price :\n",
" \n",
" try:\n",
" # try to enter de price and store it only once\n",
" price = (float(input( f\"Enter the price of {product} : \")) )\n",
" if price < 0:\n",
" raise ValueError( \"the price cannot be negative. Please enter a valid price of product.\")\n",
" else :\n",
" valid_price = True\n",
" except ValueError:\n",
" print(\"invalid input. Error: {error}. Please enter a valid price of product.\")\n",
" total_price += price\n",
" \n",
" return total_price"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "8f31cc0c-58bc-4c1e-bbfe-5d776423bb78",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the price of hat : 5\n",
"Enter the price of keychain : -2\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"invalid input. Error: {error}. Please enter a valid price of product.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the price of keychain : 4\n",
"Enter the price of t-shirt : hdf\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"invalid input. Error: {error}. Please enter a valid price of product.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the price of t-shirt : 3\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Final Test Price: 12.0\n"
]
}
],
"source": [
"# Exécution du Test\n",
"customer_orders_test = [\"hat\", \"keychain\", \"t-shirt\"]\n",
"final_price = calculate_total_price(customer_orders_test)\n",
"\n",
"print(f\"\\nFinal Test Price: {final_price:.1f}\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "fb8d2021-e5a7-49c8-8b08-272871a9504e",
"metadata": {},
"outputs": [],
"source": [
"# 3. Modify the get_customer_orders function to include error handling.\n",
"\n",
"\n",
"\n",
"def get_customer_orders(inventory): \n",
" customer_orders = []\n",
"\n",
" num_orders = -1\n",
" num_valid = False \n",
" while num_valid:\n",
" try:\n",
" num_orders_input = input(\"Enter the name of a product to order: \")\n",
" num_orders = int(num_orders_input)\n",
" if num_orders <0:\n",
" print(\"Error: The number of orders must be non-negative.\")\n",
" else :\n",
" num_valid = True\n",
" except ValueError:\n",
" print(\"Error: Invalid input. Please enter a valid non-numeric integer for the number of orders.\")\n",
" \n",
" # The enter and validation of each product\n",
" for i in range (num_orders):\n",
" order_valid = False\n",
" while not order_valid:\n",
" product_name = input (f\"Enter the name of product {i + 1}/{num_orders} to order: \").lower()\n",
" try:\n",
" product_name in inventory \n",
" except ValueError:\n",
" print (\"invalid input. Error: {error}.\")\n",
" try:\n",
" # valide the product name\n",
" if product_name not in inventory:\n",
" raise KeyError(f\"Product '{product_name}' not found in inventory.\")\n",
"\n",
" if inventory[product_name] <= 0:\n",
" raise ValueError(f\"Product '{product_name}' is out of stock.\")\n",
"\n",
" customer_orders.append(product_name)\n",
" order_valid = True\n",
" except KeyError as error:\n",
" # product name error or if the inventory is not well managed\n",
" print(f\"Invalid order: {error}. Please re-enter the product name.\")\n",
" \n",
" except ValueError as error:\n",
" # store error (quantity <= 0)\n",
" print(f\"Invalid order: {error}. Please re-enter the product name.\")\n",
" \n",
" return customer_orders"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "006fe535-14df-40b2-829d-eae7facf634d",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Test of initialize inventory\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity of t-shirts available: -2\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Invalid quantity! Please enter a non-negative value.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity of t-shirts available: 2 hat\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: invalid literal for int() with base 10: '2 hat'\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity of t-shirts available: 6\n",
"Enter the quantity of mugs available: 4\n",
"Enter the quantity of hats available: 5\n",
"Enter the quantity of books available: 2\n",
"Enter the quantity of keychains available: 4\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Order entry test\n",
"\n",
"Results of test\n",
"inventory after the initialization: {'t-shirt': 6, 'mug': 4, 'hat': 5, 'book': 2, 'keychain': 4}\n",
"Valid orders entered: []\n"
]
}
],
"source": [
"# 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",
"print(\"Test of initialize inventory\")\n",
"inventory = initialize_inventory(products)\n",
"\n",
"print()\n",
"print(\"Order entry test\")\n",
"customer_orders = get_customer_orders(inventory)\n",
"\n",
"print(\"\\nResults of test\")\n",
"print(f\"inventory after the initialization: {inventory}\")\n",
"print(f\"Valid orders entered: {customer_orders}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c2a8ed52-dbaf-41b0-a350-efc123487836",
"metadata": {},
"outputs": [],
"source": []
}
],
"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.13.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading