Skip to content
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
379 changes: 378 additions & 1 deletion lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,383 @@
"\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": "166ef48e-63f8-42d5-bfc8-3e338106fa5e",
"metadata": {},
"outputs": [],
"source": [
"# 1 - Define the function for initializing the inventory with error handling"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "64682fae-1d2f-45f9-8a1e-457e5646720e",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the quantity of t-shirts available: 2\n",
"Enter the quantity of mugs available: 2\n",
"Enter the quantity of hats available: 2\n",
"Enter the quantity of books available: 2\n",
"Enter the quantity of keychains available: 2\n"
]
}
],
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\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. Pleaase enter a valid quantity.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid quantity in numbers.\")\n",
" return inventory\n",
"\n",
"inventory = initialize_inventory(products)\n",
"\n",
"\n",
"\n",
" "
]
},
{
"cell_type": "markdown",
"id": "65a1f8a5-f892-4b83-8f94-800449b20bc3",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "738af7ae-302d-49d0-a685-b65a06c983c8",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"How many different products would you like to order? 11\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"You can only order up to 5 different products (based on the stock).\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"How many different products would you like to order? 2\n",
"Enter product 1 name: maa\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"'maa' is not in list of products.\n",
"Please try again.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter product 1 name: mug\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Added 'mug' to your orders.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter product 2 name: t-shirt\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Added 't-shirt' to your orders.\n",
"Final Customer Orders: {'t-shirt', 'mug'}\n"
]
}
],
"source": [
"def get_customer_orders(products, inventory):\n",
" avaiable_products = [p for p in products if inventory.get(p, 0) > 0]\n",
" \n",
" while True:\n",
" try:\n",
" num_orders = int(input(\"How many different products would you like to order? \")) \n",
" if num_orders <= 0:\n",
" print(\"Number of products must be greater than zero.\")\n",
" continue\n",
" if num_orders > len(avaiable_products):\n",
" print(f\"You can only order up to {len(avaiable_products)} different products (based on the stock).\")\n",
" continue\n",
" break\n",
" \n",
" except ValueError:\n",
" print(\"Please enter a valid number.\")\n",
" \n",
" customer_orders = set()\n",
" \n",
" for i in range(num_orders):\n",
" while True:\n",
" try:\n",
" product_name = input(f\"Enter product {i + 1} name: \").strip().lower() \n",
" if not product_name:\n",
" raise ValueError(\"Product name cannot be empty.\")\n",
" if product_name not in products:\n",
" raise ValueError(f\"'{product_name}' is not in list of products.\")\n",
" if inventory.get(product_name, 0) <= 0:\n",
" raise ValueError(f\"'{product_name}' is currently out of stock.\")\n",
" if product_name in customer_orders:\n",
" print(f\"'{product_name}' is already in your orders. Please enter a different product.\")\n",
" continue\n",
"\n",
" customer_orders.add(product_name)\n",
" print(f\"Added '{product_name}' to your orders.\")\n",
" break\n",
" except ValueError as e:\n",
" print(e)\n",
" print(\"Please try again.\")\n",
"\n",
" return customer_orders\n",
" \n",
"customer_orders = get_customer_orders(products, inventory)\n",
"print(\"Final Customer Orders:\", customer_orders)"
]
},
{
"cell_type": "code",
"execution_count": 36,
"id": "0f798eb4-5ffc-469d-9f69-f6eb42782444",
"metadata": {},
"outputs": [],
"source": [
"def update_inventory(inventory, customer_orders):\n",
" updated_inventory = {\n",
" product: (inventory[product] - 1 if product in customer_orders and inventory[product] > 0 else inventory[product]) for product in inventory}\n",
" return updated_inventory\n",
"\n",
"updated_inventory = update_inventory(inventory, customer_orders)"
]
},
{
"cell_type": "code",
"execution_count": 37,
"id": "b050bea2-ffb0-4851-bfa5-4e7967414d83",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"the updated inventory: t-shirt: 1, mug: 1, hat: 2, book: 2, keychain: 2\n"
]
}
],
"source": [
"def print_updated_inventory (inventory):\n",
" formatted_inventory = \", \".join(f\"{product}: {quantity}\" for product, quantity in inventory.items())\n",
" print(\"the updated inventory:\", formatted_inventory)\n",
"\n",
"print_updated_inventory(updated_inventory)"
]
},
{
"cell_type": "markdown",
"id": "0a10a046-9501-4e7d-bfa2-a6f7307b5ba2",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": 39,
"id": "6fcbe531-faef-418f-8078-437df6f8a900",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the price for t-shirt: ff\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input. Please enter a valid price.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the price for t-shirt: -122\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Price cannot be negative. Please enter a valid price.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Enter the price for t-shirt: 12\n",
"Enter the price for mug: 12\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Order prices: {'t-shirt': 12.0, 'mug': 12.0}\n",
"Total price: 24.0\n"
]
}
],
"source": [
"def get_order_prices(customer_orders):\n",
" prices = {}\n",
" total = 0.0\n",
" \n",
" for product in customer_orders:\n",
" valid_input = False\n",
" while not valid_input:\n",
" try:\n",
" price = float(input(f\"Enter the price for {product}: \"))\n",
" if price >= 0:\n",
" prices[product] = price\n",
" total += price\n",
" valid_input = True\n",
" else:\n",
" print(\"Price cannot be negative. Please enter a valid price.\")\n",
" except ValueError:\n",
" print(\"Invalid input. Please enter a valid price.\") \n",
" return prices, total\n",
"\n",
"prices, total = get_order_prices(customer_orders)\n",
"print(\"Order prices:\", prices)\n",
"print(\"Total price:\", round(total, 2))"
]
},
{
"cell_type": "code",
"execution_count": 40,
"id": "200ebd56-c86a-42bb-bd41-aac544b681ce",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The updated inventory: {'t-shirt': 1, 'mug': 1, 'hat': 2, 'book': 2, 'keychain': 2}\n"
]
}
],
"source": [
"def update_inventory(inventory, customer_orders):\n",
" for product in customer_orders:\n",
" if product in inventory and inventory[product] > 0:\n",
" inventory[product] -= 1\n",
" \n",
" updated_inventory = {product: quantity for product, quantity in inventory.items() if quantity > 0}\n",
" return updated_inventory\n",
"\n",
"updated_inventory = update_inventory(inventory, customer_orders)\n",
"print(\"The updated inventory:\", updated_inventory)\n"
]
},
{
"cell_type": "code",
"execution_count": 41,
"id": "0d8f8fa8-d3d0-4fbd-9233-37e6a5cf4b85",
"metadata": {},
"outputs": [],
"source": [
"def calculate_order_statistics(customer_orders, products):\n",
" total_products_order = len(customer_orders)\n",
" percentage = len(set(customer_orders)) / len(products) * 100\n",
" return total_products_order, percentage\n",
" \n",
"update_inventory(inventory, customer_orders)\n",
"total, percentage = calculate_order_statistics(customer_orders, products)\n"
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "d8ec46c3-b7a9-4061-b996-47275add186e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The total products ordered: 2\n",
"The percentage of unique products ordered are: 40.0 %\n"
]
}
],
"source": [
"def print_order_statistics(order_statistics): \n",
" total, percentage = order_statistics\n",
" print(\"The total products ordered: \", total)\n",
" print(\"The percentage of unique products ordered are: \", round(percentage, 2),\"%\")\n",
" \n",
"order_statistics = calculate_order_statistics(customer_orders, products)\n",
"print_order_statistics(order_statistics)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8dc641b2-e073-45a6-b924-5648023df4b2",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
Expand All @@ -90,7 +467,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.5"
}
},
"nbformat": 4,
Expand Down