Skip to content

lab delivery #438

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
250 changes: 235 additions & 15 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,29 @@
" - 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",
"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": 6,
"id": "416b3cae",
"metadata": {},
"outputs": [],
"source": [
"# Step 1: Define the function for initializing the inventory with error handling\n",
"def initialize_inventory(products):\n",
" inventory = {}\n",
Expand All @@ -37,7 +59,16 @@
" print(f\"Error: {error}\")\n",
" inventory[product] = quantity\n",
" return inventory\n",
"\n",
" initialize_inventory(products)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "62458bf8",
"metadata": {},
"outputs": [],
"source": [
"# Or, in another way:\n",
"\n",
"def initialize_inventory(products):\n",
Expand All @@ -54,29 +85,218 @@
" 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"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "04ea5e99",
"metadata": {},
"outputs": [],
"source": [
"# Step 2: Define the function to calculate total price with error handling\n",
"def calculate_total_price(inventory):\n",
" prices = {}\n",
" total_price = 0.0\n",
"\n",
" for product, quantity in inventory.items():\n",
" while True:\n",
" try:\n",
" price_input = input(f\"Enter the price of one {product}: \")\n",
" price = float(price_input)\n",
"\n",
" if price < 0:\n",
" raise ValueError(\"Price cannot be negative.\")\n",
"\n",
" prices[product] = price\n",
" total_price += price * quantity\n",
" break # Exit loop on valid input\n",
"\n",
" except ValueError as error:\n",
" print(f\"Error: {error}. Please enter a valid non-negative number.\")\n",
"\n",
" return total_price, prices\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "38ec5250",
"metadata": {},
"outputs": [],
"source": [
"# Step 3: Modify the `get_customer_orders` function to include error handling.\n",
"def get_customer_orders(inventory):\n",
" orders = {}\n",
"\n",
" # Step 1: Ask for number of orders\n",
" while True:\n",
" try:\n",
" num_orders_input = input(\"How many different products would the customer like to order? \")\n",
" num_orders = int(num_orders_input)\n",
"\n",
" if num_orders < 0:\n",
" raise ValueError(\"Number of orders cannot be negative.\")\n",
" break\n",
" except ValueError as error:\n",
" print(f\"Error: {error}. Please enter a valid non-negative integer.\")\n",
"\n",
" # Step 2: Ask for each product and quantity\n",
" for _ in range(num_orders):\n",
" while True:\n",
" product = input(\"Enter the product name: \").strip().lower()\n",
"\n",
" if product not in inventory:\n",
" print(\"Error: This product is not in the inventory. Please try again.\")\n",
" elif inventory[product] == 0:\n",
" print(f\"Error: {product.capitalize()} is out of stock.\")\n",
" else:\n",
" break\n",
"\n",
" # Step 3: Ask for quantity of that product\n",
" while True:\n",
" try:\n",
" quantity_input = input(f\"Enter quantity of {product} (Available: {inventory[product]}): \")\n",
" quantity = int(quantity_input)\n",
"\n",
" if quantity <= 0:\n",
" raise ValueError(\"Quantity must be greater than zero.\")\n",
" if quantity > inventory[product]:\n",
" raise ValueError(f\"Only {inventory[product]} {product}s available.\")\n",
"\n",
" orders[product] = quantity\n",
" break\n",
" except ValueError as error:\n",
" print(f\"Error: {error}. Please try again.\")\n",
"\n",
" return orders"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "9b5d987c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"=== Initialize Inventory ===\n",
"Error: invalid literal for int() with base 10: '%'. Please enter a valid non-negative integer.\n",
"\n",
"=== Set Prices ===\n",
"\n",
"=== Customer Orders ===\n",
"Error: This product is not in the inventory. Please try again.\n",
"Error: This product is not in the inventory. Please try again.\n",
"\n",
"=== Summary ===\n",
"Inventory: {'t-shirt': 5, 'mug': 10, 'hat': 15, 'book': 20, 'keychain': 25}\n",
"Prices: {'t-shirt': 5.0, 'mug': 3.0, 'hat': 6.0, 'book': 3.0, 'keychain': 4.0}\n",
"Orders: {'keychain': 4, 'hat': 10, 'mug': 2, 'book': 6, 't-shirt': 2}\n"
]
}
],
"source": [
"# Finalized functions to run the full program\n",
"# Step 1: Initialize Inventory with Error Handling\n",
"def initialize_inventory(products):\n",
" inventory = {}\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" quantity_input = input(f\"Enter the quantity of {product}s available: \")\n",
" quantity = int(quantity_input)\n",
" if quantity < 0:\n",
" raise ValueError(\"Quantity cannot be negative.\")\n",
" inventory[product] = quantity\n",
" break\n",
" except ValueError as error:\n",
" print(f\"Error: {error}. Please enter a valid non-negative integer.\")\n",
" return inventory\n",
"```\n",
"\n",
"Let's enhance your code by implementing error handling to handle invalid inputs.\n",
"# Step 2: Calculate Total Inventory Price with Error Handling\n",
"def calculate_total_price(inventory):\n",
" prices = {}\n",
" total_price = 0.0\n",
" for product in inventory:\n",
" while True:\n",
" try:\n",
" price_input = input(f\"Enter the price of one {product}: \")\n",
" price = float(price_input)\n",
" if price < 0:\n",
" raise ValueError(\"Price cannot be negative.\")\n",
" prices[product] = price\n",
" total_price += price * inventory[product]\n",
" break\n",
" except ValueError as error:\n",
" print(f\"Error: {error}. Please enter a valid non-negative number.\")\n",
" return total_price, prices\n",
"\n",
"Follow the steps below to complete the exercise:\n",
"# Step 3: Get Customer Orders with Error Handling\n",
"def get_customer_orders(inventory):\n",
" orders = {}\n",
" while True:\n",
" try:\n",
" num_orders_input = input(\"How many different products would the customer like to order? \")\n",
" num_orders = int(num_orders_input)\n",
" if num_orders < 0:\n",
" raise ValueError(\"Number of orders cannot be negative.\")\n",
" break\n",
" except ValueError as error:\n",
" print(f\"Error: {error}. Please enter a valid non-negative integer.\")\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",
" for _ in range(num_orders):\n",
" while True:\n",
" product = input(\"Enter the product name: \").strip().lower()\n",
" if product not in inventory:\n",
" print(\"Error: This product is not in the inventory. Please try again.\")\n",
" elif inventory[product] == 0:\n",
" print(f\"Error: {product.capitalize()} is out of stock.\")\n",
" else:\n",
" break\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",
" while True:\n",
" try:\n",
" quantity_input = input(f\"Enter quantity of {product} (Available: {inventory[product]}): \")\n",
" quantity = int(quantity_input)\n",
" if quantity <= 0:\n",
" raise ValueError(\"Quantity must be greater than zero.\")\n",
" if quantity > inventory[product]:\n",
" raise ValueError(f\"Only {inventory[product]} {product}s available.\")\n",
" orders[product] = quantity\n",
" break\n",
" except ValueError as error:\n",
" print(f\"Error: {error}. Please try again.\")\n",
" return orders\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"
"# Step 4: Run Full Program and Test\n",
"def main():\n",
" products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
" print(\"=== Initialize Inventory ===\")\n",
" inventory = initialize_inventory(products)\n",
"\n",
" print(\"\\n=== Set Prices ===\")\n",
" total_price, prices = calculate_total_price(inventory)\n",
"\n",
" print(\"\\n=== Customer Orders ===\")\n",
" orders = get_customer_orders(inventory)\n",
"\n",
" print(\"\\n=== Summary ===\")\n",
" print(\"Inventory:\", inventory)\n",
" print(\"Prices:\", prices)\n",
" print(\"Orders:\", orders)\n",
"\n",
"if __name__ == \"__main__\":\n",
" main()\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "base",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +310,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.12.7"
}
},
"nbformat": 4,
Expand Down