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
388 changes: 292 additions & 96 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
@@ -1,98 +1,294 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e",
"metadata": {},
"source": [
"# Lab | Error Handling"
]
"cells": [
{
"cell_type": "markdown",
"id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e",
"metadata": {
"id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e"
},
"source": [
"# Lab | Error Handling"
]
},
{
"cell_type": "markdown",
"id": "bc99b386-7508-47a0-bcdb-d969deaf6c8b",
"metadata": {
"id": "bc99b386-7508-47a0-bcdb-d969deaf6c8b"
},
"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",
"source": [
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"\n",
"\n",
"def create_inventory(products):\n",
" \"\"\"Ask the user for the initial quantity of each product.\"\"\"\n",
" inventory = {}\n",
"\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" quantity = int(input(f\"Enter quantity for {product}: \"))\n",
"\n",
" if quantity < 0:\n",
" raise ValueError(\"Quantity cannot be negative\")\n",
"\n",
" inventory[product] = quantity\n",
" break\n",
"\n",
" except ValueError as error:\n",
" print(f\"Invalid quantity: {error}. Please enter a whole number.\")\n",
"\n",
" return inventory\n",
"\n",
"\n",
"def get_customer_orders(inventory):\n",
" \"\"\"Ask how many products the customer wants and validate each order.\"\"\"\n",
" while True:\n",
" try:\n",
" number_of_orders = int(\n",
" input(\"How many different products would you like to order? \")\n",
" )\n",
"\n",
" if number_of_orders < 0:\n",
" raise ValueError(\"The number of orders cannot be negative\")\n",
"\n",
" available_products = sum(\n",
" 1 for quantity in inventory.values() if quantity > 0\n",
" )\n",
"\n",
" if number_of_orders > available_products:\n",
" raise ValueError(\n",
" f\"Only {available_products} different products are available\"\n",
" )\n",
"\n",
" break\n",
"\n",
" except ValueError as error:\n",
" print(f\"Invalid number of orders: {error}.\")\n",
"\n",
" customer_orders = set()\n",
"\n",
" while len(customer_orders) < number_of_orders:\n",
" try:\n",
" order = input(\n",
" f\"Enter product {len(customer_orders) + 1}: \"\n",
" ).strip().lower()\n",
"\n",
" if order not in inventory:\n",
" raise ValueError(f\"'{order}' is not a valid product\")\n",
"\n",
" if inventory[order] <= 0:\n",
" raise ValueError(f\"'{order}' is out of stock\")\n",
"\n",
" if order in customer_orders:\n",
" raise ValueError(f\"'{order}' has already been ordered\")\n",
"\n",
" customer_orders.add(order)\n",
"\n",
" except ValueError as error:\n",
" print(f\"Invalid product: {error}. Please try again.\")\n",
"\n",
" return customer_orders\n",
"\n",
"\n",
"def calculate_total_price(customer_orders):\n",
" \"\"\"Ask for and validate the price of every ordered product.\"\"\"\n",
" total_price = 0\n",
"\n",
" for product in customer_orders:\n",
" while True:\n",
" try:\n",
" price = float(input(f\"Enter the price for {product}: €\"))\n",
"\n",
" if price < 0:\n",
" raise ValueError(\"Price cannot be negative\")\n",
"\n",
" total_price += price\n",
" break\n",
"\n",
" except ValueError as error:\n",
" print(f\"Invalid price: {error}. Please enter a valid number.\")\n",
"\n",
" return total_price\n",
"\n",
"\n",
"def update_inventory(customer_orders, inventory):\n",
" \"\"\"Remove one unit of every ordered product from the inventory.\"\"\"\n",
" for product in customer_orders:\n",
" inventory[product] -= 1\n",
"\n",
"\n",
"def display_order_statistics(customer_orders, products):\n",
" \"\"\"Calculate and display statistics about the order.\"\"\"\n",
" total_products_ordered = len(customer_orders)\n",
" percentage_ordered = (\n",
" total_products_ordered / len(products)\n",
" ) * 100\n",
"\n",
" print(\"\\nOrder Statistics:\")\n",
" print(\"Total Products Ordered:\", total_products_ordered)\n",
" print(f\"Percentage of Products Ordered: {percentage_ordered:.0f}%\")\n",
"\n",
"\n",
"def display_inventory(inventory):\n",
" \"\"\"Display the remaining inventory.\"\"\"\n",
" print(\"\\nUpdated Inventory:\")\n",
"\n",
" for product, quantity in inventory.items():\n",
" print(f\"{product}: {quantity}\")\n",
"\n",
"\n",
"# Main program\n",
"inventory = create_inventory(products)\n",
"\n",
"customer_orders = get_customer_orders(inventory)\n",
"\n",
"total_price = calculate_total_price(customer_orders)\n",
"\n",
"update_inventory(customer_orders, inventory)\n",
"\n",
"print(\"\\nCustomer Orders:\", customer_orders)\n",
"\n",
"display_order_statistics(customer_orders, products)\n",
"\n",
"print(f\"Total Price: €{total_price:.2f}\")\n",
"\n",
"display_inventory(inventory)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Ssm8XBmIgC0F",
"outputId": "b4033924-55ea-4d5e-919c-d475bce278ea"
},
"id": "Ssm8XBmIgC0F",
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Enter quantity for t-shirt: 7\n",
"Enter quantity for mug: 5\n",
"Enter quantity for hat: 7\n",
"Enter quantity for book: 8\n",
"Enter quantity for keychain: 9\n",
"How many different products would you like to order? 4\n",
"Enter product 1: mug\n",
"Enter product 2: hat\n",
"Enter product 3: book\n",
"Enter product 4: t-shit\n",
"Invalid product: 't-shit' is not a valid product. Please try again.\n",
"Enter product 4: t-shirt\n",
"Enter the price for t-shirt: €10\n",
"Enter the price for hat: €3\n",
"Enter the price for book: €7\n",
"Enter the price for mug: €3\n",
"\n",
"Customer Orders: {'t-shirt', 'hat', 'book', 'mug'}\n",
"\n",
"Order Statistics:\n",
"Total Products Ordered: 4\n",
"Percentage of Products Ordered: 80%\n",
"Total Price: €23.00\n",
"\n",
"Updated Inventory:\n",
"t-shirt: 6\n",
"mug: 4\n",
"hat: 6\n",
"book: 7\n",
"keychain: 9\n"
]
}
]
}
],
"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.9.13"
},
"colab": {
"provenance": []
}
},
{
"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"
]
}
],
"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.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
"nbformat": 4,
"nbformat_minor": 5
}