diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index f4c6ef6..6627f0f 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -2,10 +2,11 @@ "cells": [ { "cell_type": "markdown", - "id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e", + "id": "40485476", "metadata": {}, "source": [ - "# Lab | Error Handling" + "# Lab | Error Handling\n", + "---" ] }, { @@ -18,8 +19,8 @@ "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", + " - **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", @@ -72,11 +73,364 @@ "\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": "markdown", + "id": "549c919f", + "metadata": {}, + "source": [ + "---\n", + "---\n", + "# Solved Lab | Error Handling" + ] + }, + { + "cell_type": "markdown", + "id": "399e7e87", + "metadata": {}, + "source": [ + "---\n", + "### STEP 1\n", + "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**." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4f673274", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Invalid input: invalid literal for int() with base 10: 'a'. Please enter a non-negative integer.\n", + "Invalid input: invalid literal for int() with base 10: 'f'. Please enter a non-negative integer.\n", + "Invalid input: invalid literal for int() with base 10: 'g'. Please enter a non-negative integer.\n", + "Invalid input: invalid literal for int() with base 10: 'apple'. Please enter a non-negative integer.\n", + "Invalid input: invalid literal for int() with base 10: 'Apple'. Please enter a non-negative integer.\n", + "Invalid input: invalid literal for int() with base 10: 'Apples'. Please enter a non-negative integer.\n", + "Invalid input: invalid literal for int() with base 10: 'Cake'. Please enter a non-negative integer.\n", + "Invalid input: invalid literal for int() with base 10: ''. Please enter a non-negative integer.\n", + "Invalid input: invalid literal for int() with base 10: ''. Please enter a non-negative integer.\n" + ] + } + ], + "source": [ + "# Step 1: Define the function for initializing the inventory with error handling\n", + "def initialize_inventory(products):\n", + " \"\"\"\n", + " Initialize inventory quantities for a list of products.\n", + " Ensures that the user enters valid non-negative integers.\n", + " \n", + " Args:\n", + " products (list): List of product names.\n", + " \n", + " Returns:\n", + " dict: Dictionary with product names as keys and quantities as values.\n", + " \"\"\"\n", + " inventory = {}\n", + " \n", + " for product in products:\n", + " while True:\n", + " try:\n", + " # Ask the user for quantity\n", + " quantity = input(f\"Enter quantity for {product}: \")\n", + " \n", + " # Convert input to integer\n", + " quantity = int(quantity)\n", + " \n", + " # Check for negative values\n", + " if quantity < 0:\n", + " raise ValueError(\"Quantity cannot be negative.\")\n", + " \n", + " # Valid quantity, store it and break the loop\n", + " inventory[product] = quantity\n", + " break\n", + " \n", + " except ValueError as e:\n", + " # Handle non-numeric or negative inputs\n", + " print(f\"Invalid input: {e}. Please enter a non-negative integer.\")\n", + " \n", + " return inventory\n", + "\n", + "# Test the function:\n", + "products_list = [\"Apples\", \"Bananas\", \"Oranges\"]\n", + "inventory = initialize_inventory(products_list)\n", + "print(\"Inventory initialized:\", inventory)\n" + ] + }, + { + "cell_type": "markdown", + "id": "7711e9ff", + "metadata": {}, + "source": [ + "---\n", + "### STEP 2\n", + "2. Modify the `calculate_total_price` function to include error handling.\n", + " \n", + " - If the user enters an invalid price (e.g., a negative value or a non-numeric value),\n", + " - display an error message and ask them to re-enter the price for that product.\n", + " \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": 1, + "id": "1136ebce", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Invalid input: could not convert string to float: 'a'. Please enter a non-negative number.\n", + "Total price: $45.00\n" + ] + } + ], + "source": [ + "def calculate_total_price(products):\n", + " \"\"\"\n", + " Ask the user to enter the price for each product and calculate the total price.\n", + " Ensures valid, non-negative numeric input.\n", + "\n", + " Args:\n", + " products (list): List of product names.\n", + "\n", + " Returns:\n", + " float: Total price of all products.\n", + " \"\"\"\n", + " total_price = 0.0\n", + " \n", + " for product in products:\n", + " while True:\n", + " try:\n", + " # Ask user for the price\n", + " price = input(f\"Enter price for {product}: \")\n", + " \n", + " # Convert input to float\n", + " price = float(price)\n", + " \n", + " # Check for negative price\n", + " if price < 0:\n", + " raise ValueError(\"Price cannot be negative.\")\n", + " \n", + " # Valid price, add to total and break loop\n", + " total_price += price\n", + " break\n", + " \n", + " except ValueError as e:\n", + " print(f\"Invalid input: {e}. Please enter a non-negative number.\")\n", + " \n", + " return total_price\n", + "\n", + "# Example usage:\n", + "products_list = [\"Apples\", \"Bananas\", \"Oranges\"]\n", + "total = calculate_total_price(products_list)\n", + "print(f\"Total price: ${total:.2f}\")\n" + ] + }, + { + "cell_type": "markdown", + "id": "63b63ca9", + "metadata": {}, + "source": [ + "---\n", + "### STEP 3\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), \n", + " - 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, \n", + " - display an error message and ask them to re-enter the product name. \n", + " - *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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ae63c5c8", + "metadata": {}, + "outputs": [], + "source": [ + "def get_customer_orders(inventory):\n", + " \"\"\"\n", + " Ask the user for their orders, including quantity and product name.\n", + " Validates:\n", + " - Number of orders (non-negative integer)\n", + " - Product exists in inventory\n", + " - Product has available stock\n", + "\n", + " Args:\n", + " inventory (dict): Dictionary of product names and available quantities\n", + "\n", + " Returns:\n", + " dict: Customer orders with product names and ordered quantities\n", + " \"\"\"\n", + " orders = {}\n", + "\n", + " print(\"\\nEnter your orders:\")\n", + "\n", + " while True:\n", + " try:\n", + " num_orders = input(\"How many different products do you want to order? \")\n", + " num_orders = int(num_orders)\n", + " if num_orders < 0:\n", + " raise ValueError(\"Number of orders cannot be negative.\")\n", + " break\n", + " except ValueError as e:\n", + " print(f\"Invalid input: {e}. Please enter a non-negative integer.\")\n", + "\n", + " for i in range(num_orders):\n", + " while True:\n", + " product_name = input(f\"Enter product name for order #{i+1}: \").strip()\n", + " \n", + " # Check if product exists in inventory\n", + " if product_name not in inventory:\n", + " print(\"Invalid product name. Please choose a product from the inventory.\")\n", + " continue\n", + " \n", + " # Check if product has stock available\n", + " if inventory[product_name] == 0:\n", + " print(f\"Sorry, {product_name} is out of stock. Please choose another product.\")\n", + " continue\n", + " \n", + " # Ask for quantity\n", + " while True:\n", + " try:\n", + " quantity = input(f\"Enter quantity for {product_name}: \")\n", + " quantity = int(quantity)\n", + " if quantity < 0:\n", + " raise ValueError(\"Quantity cannot be negative.\")\n", + " if quantity > inventory[product_name]:\n", + " raise ValueError(f\"Only {inventory[product_name]} units of {product_name} available.\")\n", + " break\n", + " except ValueError as e:\n", + " print(f\"Invalid input: {e}. Please try again.\")\n", + " \n", + " # Save order and reduce inventory\n", + " orders[product_name] = quantity\n", + " inventory[product_name] -= quantity\n", + " break\n", + "\n", + " return orders\n", + "\n", + "# Example usage\n", + "inventory = {\"Apples\": 10, \"Bananas\": 5, \"Oranges\": 8}\n", + "customer_orders = get_customer_orders(inventory)\n", + "print(\"\\nCustomer Orders:\", customer_orders)\n", + "print(\"Updated Inventory:\", inventory)\n" + ] + }, + { + "cell_type": "markdown", + "id": "f55ac6e6", + "metadata": {}, + "source": [ + "---\n", + "### STEP 4\n", + "4. Test your code by running the program and deliberately entering invalid quantities and product names. \n", + "- Make sure the error handling mechanism works as expected." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e342261e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error: Enter a whole number.\n", + "Error: Enter a whole number.\n", + "Error: Enter a whole number.\n", + "Error: Enter a whole number.\n", + "Error: Enter a whole number.\n", + "Error: Enter a whole number.\n", + "Error: 'ddd' not in inventory. Available: ['Chocolate Bar', 'Truffle Box', 'Candy Cane']\n", + "Error: 'chocolate bar' not in inventory. Available: ['Chocolate Bar', 'Truffle Box', 'Candy Cane']\n", + "Error: 'hehe' not in inventory. Available: ['Chocolate Bar', 'Truffle Box', 'Candy Cane']\n", + "Error: 'aa' not in inventory. Available: ['Chocolate Bar', 'Truffle Box', 'Candy Cane']\n" + ] + } + ], + "source": [ + "def initialize_inventory(products):\n", + " \"\"\"Initialize inventory with error handling for quantities\"\"\"\n", + " inventory = {}\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " quantity = int(input(f\"Enter quantity for {product}: \"))\n", + " if quantity < 0:\n", + " print(\"Error: Quantity cannot be negative.\")\n", + " continue\n", + " inventory[product] = quantity\n", + " break\n", + " except ValueError:\n", + " print(\"Error: Enter a whole number.\")\n", + " return inventory\n", + "\n", + "def get_customer_orders(inventory):\n", + " customer_orders = []\n", + " while True:\n", + " try:\n", + " num_orders = int(input(\"Enter number of orders: \"))\n", + " if num_orders < 0:\n", + " print(\"Error: Number of orders cannot be negative.\")\n", + " continue\n", + " break\n", + " except ValueError:\n", + " print(\"Error: Enter a whole number.\")\n", + " \n", + " for _ in range(num_orders):\n", + " while True:\n", + " product = input(\"Enter product name: \").strip()\n", + " if product not in inventory:\n", + " print(f\"Error: '{product}' not in inventory. Available: {list(inventory.keys())}\")\n", + " continue\n", + " if inventory[product] <= 0:\n", + " print(f\"Error: '{product}' out of stock.\")\n", + " continue\n", + " customer_orders.append(product)\n", + " break\n", + " return customer_orders\n", + "\n", + "def calculate_total_price(products):\n", + " total_price = 0.0\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " price = float(input(f\"Enter price for {product}: $\"))\n", + " if price < 0:\n", + " print(\"Error: Price cannot be negative.\")\n", + " continue\n", + " total_price += price\n", + " break\n", + " except ValueError:\n", + " print(\"Error: Enter numeric value.\")\n", + " return total_price\n", + "\n", + "# Main program\n", + "if __name__ == \"__main__\":\n", + " products = [\"Chocolate Bar\", \"Truffle Box\", \"Candy Cane\"]\n", + " inventory = initialize_inventory(products)\n", + " orders = get_customer_orders(inventory)\n", + " total = calculate_total_price(orders)\n", + " print(f\"\\nFinal order: {orders}\")\n", + " print(f\"Total price: ${total:.2f}\")[conversation_history:6]\n" + ] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "base", "language": "python", "name": "python3" }, @@ -90,7 +444,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.13.9" } }, "nbformat": 4,