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
339 changes: 339 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,339 @@
{
"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": 19,
"id": "867ce320-d598-482d-9669-e8fb74f931c6",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"please enter the quantity of t-shirt: 0\n",
"please enter the quantity of mug: 4\n",
"please enter the quantity of hat: -1\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid quantity! Please enter a non-negative value.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"please enter the quantity of hat: 6\n",
"please enter the quantity of book: 5\n",
"please enter the quantity of keychain: 9\n"
]
},
{
"data": {
"text/plain": [
"{'t-shirt': 0, 'mug': 4, 'hat': 6, 'book': 5, 'keychain': 9}"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"products=[\"t-shirt\",\"mug\",\"hat\",\"book\",\"keychain\"]\n",
"\n",
"# def valid_quantity(product):\n",
"# is_q_valid=False\n",
"# while not is_q_valid:\n",
"# try:\n",
"# quantity=int(input(f\"please enter the quantity of {product}:\"))\n",
"# # if quantity < 0:\n",
"# # raise ValueError(\"Invalid quantity! Please enter a non-negative value.\")\n",
"# assert quantity > 0\n",
"# is_q_valid=True\n",
"# except ValueError:\n",
"# print(\"Invalid input. Please enter a valid quantity.\")\n",
"# except AssertionError:\n",
"# print(\"Invalid quantity! Please enter a non-negative value.\")\n",
"# return quantity\n",
"\n",
"def valid_value(product,attri):\n",
" is_valid=False\n",
" while not is_valid:\n",
" try:\n",
" if attri==\"quantity\":\n",
" value=int(input(f\"please enter the quantity of {product}:\"))\n",
" assert value>=0\n",
" elif attri==\"price\":\n",
" value=float(input(f\"please input the price of {product}:\"))\n",
" assert value>0\n",
" elif attri==\"order number\":\n",
" value=int(input(\"please enter how many orders you want to have:\"))\n",
" assert value>=0\n",
" elif attri==\"product name\":\n",
" value=input(\"please enter the product name that you want to buy:\").strip().lower()\n",
" if not(value in product):\n",
" raise ValueError\n",
" assert product[value] >0\n",
" else:\n",
" is_valid=True\n",
" value = None\n",
" raise AttributeError(f\"there is no {attri}, pease check your function\")\n",
" is_valid=True \n",
" except ValueError:\n",
" print(f\"Invalid input. Please enter a valid {attri}.\")\n",
" except AssertionError:\n",
" if attri==\"product name\":\n",
" print(f\"{value} is not available, please enter a new product.\")\n",
" elif attri==\"price\":\n",
" print(f\"Invalid {attri}! Please enter a value more than 0.\")\n",
" else:\n",
" print(f\"Invalid {attri}! Please enter a non-negative value.\")\n",
" return value\n",
" \n",
"def initialize_inventory(products_list:list) -> dict:\n",
" ini_inventory={product:valid_value(product,\"quantity\") for product in products_list}\n",
" return ini_inventory\n",
"\n",
"inventory=initialize_inventory(products)\n",
"inventory"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "3f3500ec-8637-4ae4-8be9-68f8d20e00fa",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"please enter how many orders you want to have: t-shirt\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input. Please enter a valid order number.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"please enter how many orders you want to have: 1\n",
"please enter the product name that you want to buy: t-shirt\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"t-shirtis not available, please enter a new product.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"please enter the product name that you want to buy: mug\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"def get_customer_orders(products):\n",
" order_number=valid_value(products,\"order number\")\n",
" if order_number != 0:\n",
" customer_orders={valid_value(products,\"product name\") for i in range(order_number)}\n",
" else:\n",
" customer_orders=set()\n",
" return customer_orders\n",
" \n",
"customer_orders=get_customer_orders(inventory)\n",
"print(len(customer_orders))"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "229b5858-02c5-4a65-b383-f47158a81e14",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"please input the price of {'mug'}: -1\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid price! Please enter a value more than 0.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"please input the price of {'mug'}: 0\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid price! Please enter a value more than 0.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"please input the price of {'mug'}: 5\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"total price: 5.0\n"
]
}
],
"source": [
"# def valid_price(product):\n",
"# is_price_valid=False\n",
"# while not is_price_valid:\n",
"# try:\n",
"# price=float(input(f\"please input the price of {product}:\"))\n",
"# assert quantity > 0\n",
"# is_q_valid=True\n",
"# except ValueError:\n",
"# print(\"Invalid input. Please enter a valid quantity.\")\n",
"# except AssertionError:\n",
"# print(\"Invalid price! Please enter a non-negative value.\")\n",
"\n",
"def calculate_price(products):\n",
" return sum(valid_value(products,\"price\") for i in products)\n",
"\n",
"print(\"total price:\",calculate_price(customer_orders))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6ab59cff-35c9-4d47-85a8-49009f50dca1",
"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.10.14"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading