diff --git a/.ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb b/.ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb new file mode 100644 index 0000000..1876a2f --- /dev/null +++ b/.ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb @@ -0,0 +1,315 @@ +{ + "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": 20, + "id": "ba8b09cf-fbe5-4580-9a75-3bb7c8bd539e", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter the quantity of t-shirts available: 10\n", + "Enter the quantity of mugs available: 11\n", + "Enter the quantity of hats available: 12\n", + "Enter the quantity of books available: 13\n", + "Enter the quantity of keychains available: 14\n" + ] + } + ], + "source": [ + "products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n", + "inventory = initialize_inventory(products)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "3cd6470c-357b-4fbf-8710-1b20eb3964b2", + "metadata": {}, + "outputs": [], + "source": [ + "def initialize_inventory(products):\n", + " inventory = {}\n", + " for item in products:\n", + " valid_quantity = False\n", + " while not valid_quantity:\n", + " try:\n", + " quantity = int(input(f\"Enter the quantity of {item}s available: \"))\n", + " if quantity < 0:\n", + " raise ValueError(\"Quantity cannot be negative. Please enter a valid quantity.\")\n", + " inventory[item] = quantity\n", + " valid_quantity = True\n", + " except ValueError as error:\n", + " print(f\"Error: {error}. Please enter a valid number.\")\n", + " return inventory" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "24935485-d879-40ec-94e2-abdc67adc479", + "metadata": {}, + "outputs": [], + "source": [ + "def total_price(customer_orders):\n", + " prices = []\n", + " for order in customer_orders:\n", + " valid_price = False\n", + " while not valid_price:\n", + " try:\n", + " price = float(input(f\"Enter the price of {order}: \"))\n", + " if price < 0:\n", + " raise ValueError(\"Price cannot be negative.\")\n", + " prices.append(price)\n", + " valid_price = True\n", + " except ValueError as error:\n", + " print(f\"Invalid input: {error} Please enter a valid numeric price.\")\n", + " \n", + " total = sum(prices)\n", + " print(f\"Total price of products are: {total}\")\n", + " return total" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "fb57dad2-2afa-4142-bad2-650642dca32b", + "metadata": {}, + "outputs": [], + "source": [ + "def get_customer_orders(inventory):\n", + " customer_orders = set()\n", + " add_another_product = \"yes\"\n", + " \n", + " while add_another_product == \"yes\":\n", + " valid_order = False\n", + " while not valid_order:\n", + " try:\n", + " x = input(\"Input order product name: \").strip()\n", + " \n", + " # Check if product exists in inventory\n", + " if x not in inventory:\n", + " raise KeyError(f\"'{x}' is not available in the inventory.\")\n", + " \n", + " # Check if product is out of stock\n", + " if inventory[x] <= 0:\n", + " raise ValueError(f\"Sorry, '{x}' is currently out of stock.\")\n", + " \n", + " customer_orders.add(x)\n", + " valid_order = True\n", + " except (KeyError, ValueError) as error:\n", + " print(f\"Error: {error}. Please choose a valid product from the inventory.\")\n", + " \n", + " add_another_product = input(\"Do you want to add another product? (yes/no): \").strip().lower()\n", + " \n", + " return customer_orders" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "3a616599-0d6c-4a5e-98fb-a1d9bdccb8ae", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Input order product name: hat\n", + "Do you want to add another product? (yes/no): yes\n", + "Input order product name: mug\n", + "Do you want to add another product? (yes/no): no\n" + ] + } + ], + "source": [ + "customer_orders = get_customer_orders(inventory)" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "81922add-f2fe-40e1-b080-30a45b94d675", + "metadata": {}, + "outputs": [], + "source": [ + "def update_inventory(customer_orders, inventory):\n", + " for item in customer_orders:\n", + " if item in inventory:\n", + " inventory[item] = inventory[item] - 1\n", + " return inventory" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "ecba47d9-f7be-4b7c-97e0-301f17efbe42", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Order Statistics:\n", + "Total Products Ordered:2\n", + "Percentage of Products Ordered:40.0\n", + "{'t-shirt': 10, 'mug': 10, 'hat': 11, 'book': 13, 'keychain': 14}\n", + "dict_items([('t-shirt', 10), ('mug', 10), ('hat', 11), ('book', 13), ('keychain', 14)])\n", + "dict_keys(['t-shirt', 'mug', 'hat', 'book', 'keychain'])\n", + "dict_values([10, 10, 11, 13, 14])\n", + "('t-shirt', 10)\n", + "('mug', 10)\n", + "('hat', 11)\n", + "('book', 13)\n", + "('keychain', 14)\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter the price of hat: 2\n", + "Enter the price of mug: 4\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Total price of products are: 6.0\n" + ] + }, + { + "data": { + "text/plain": [ + "6.0" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Step A: Update the inventory quantities based on customer orders\n", + "update_inventory(customer_orders, inventory)\n", + "\n", + "# Step B: Calculate order statistics\n", + "order_status = calculate_order_statistics(customer_orders, products)\n", + "\n", + "# Step C: Print order statistics\n", + "print_order_statistics(order_status)\n", + "\n", + "# Step D: Print the updated inventory details\n", + "print_updated_inventory(inventory)\n", + "\n", + "# Step E: Calculate and print the total price (using your enhanced total_price function with error handling)\n", + "total_price(customer_orders)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cccf40b3-b5f8-4d43-8a25-7d84cfa5a365", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python [conda env:base] *", + "language": "python", + "name": "conda-base-py" + }, + "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.13.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index f4c6ef6..1876a2f 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -72,13 +72,230 @@ "\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": 20, + "id": "ba8b09cf-fbe5-4580-9a75-3bb7c8bd539e", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter the quantity of t-shirts available: 10\n", + "Enter the quantity of mugs available: 11\n", + "Enter the quantity of hats available: 12\n", + "Enter the quantity of books available: 13\n", + "Enter the quantity of keychains available: 14\n" + ] + } + ], + "source": [ + "products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n", + "inventory = initialize_inventory(products)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "3cd6470c-357b-4fbf-8710-1b20eb3964b2", + "metadata": {}, + "outputs": [], + "source": [ + "def initialize_inventory(products):\n", + " inventory = {}\n", + " for item in products:\n", + " valid_quantity = False\n", + " while not valid_quantity:\n", + " try:\n", + " quantity = int(input(f\"Enter the quantity of {item}s available: \"))\n", + " if quantity < 0:\n", + " raise ValueError(\"Quantity cannot be negative. Please enter a valid quantity.\")\n", + " inventory[item] = quantity\n", + " valid_quantity = True\n", + " except ValueError as error:\n", + " print(f\"Error: {error}. Please enter a valid number.\")\n", + " return inventory" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "24935485-d879-40ec-94e2-abdc67adc479", + "metadata": {}, + "outputs": [], + "source": [ + "def total_price(customer_orders):\n", + " prices = []\n", + " for order in customer_orders:\n", + " valid_price = False\n", + " while not valid_price:\n", + " try:\n", + " price = float(input(f\"Enter the price of {order}: \"))\n", + " if price < 0:\n", + " raise ValueError(\"Price cannot be negative.\")\n", + " prices.append(price)\n", + " valid_price = True\n", + " except ValueError as error:\n", + " print(f\"Invalid input: {error} Please enter a valid numeric price.\")\n", + " \n", + " total = sum(prices)\n", + " print(f\"Total price of products are: {total}\")\n", + " return total" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "fb57dad2-2afa-4142-bad2-650642dca32b", + "metadata": {}, + "outputs": [], + "source": [ + "def get_customer_orders(inventory):\n", + " customer_orders = set()\n", + " add_another_product = \"yes\"\n", + " \n", + " while add_another_product == \"yes\":\n", + " valid_order = False\n", + " while not valid_order:\n", + " try:\n", + " x = input(\"Input order product name: \").strip()\n", + " \n", + " # Check if product exists in inventory\n", + " if x not in inventory:\n", + " raise KeyError(f\"'{x}' is not available in the inventory.\")\n", + " \n", + " # Check if product is out of stock\n", + " if inventory[x] <= 0:\n", + " raise ValueError(f\"Sorry, '{x}' is currently out of stock.\")\n", + " \n", + " customer_orders.add(x)\n", + " valid_order = True\n", + " except (KeyError, ValueError) as error:\n", + " print(f\"Error: {error}. Please choose a valid product from the inventory.\")\n", + " \n", + " add_another_product = input(\"Do you want to add another product? (yes/no): \").strip().lower()\n", + " \n", + " return customer_orders" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "3a616599-0d6c-4a5e-98fb-a1d9bdccb8ae", + "metadata": {}, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Input order product name: hat\n", + "Do you want to add another product? (yes/no): yes\n", + "Input order product name: mug\n", + "Do you want to add another product? (yes/no): no\n" + ] + } + ], + "source": [ + "customer_orders = get_customer_orders(inventory)" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "81922add-f2fe-40e1-b080-30a45b94d675", + "metadata": {}, + "outputs": [], + "source": [ + "def update_inventory(customer_orders, inventory):\n", + " for item in customer_orders:\n", + " if item in inventory:\n", + " inventory[item] = inventory[item] - 1\n", + " return inventory" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "ecba47d9-f7be-4b7c-97e0-301f17efbe42", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Order Statistics:\n", + "Total Products Ordered:2\n", + "Percentage of Products Ordered:40.0\n", + "{'t-shirt': 10, 'mug': 10, 'hat': 11, 'book': 13, 'keychain': 14}\n", + "dict_items([('t-shirt', 10), ('mug', 10), ('hat', 11), ('book', 13), ('keychain', 14)])\n", + "dict_keys(['t-shirt', 'mug', 'hat', 'book', 'keychain'])\n", + "dict_values([10, 10, 11, 13, 14])\n", + "('t-shirt', 10)\n", + "('mug', 10)\n", + "('hat', 11)\n", + "('book', 13)\n", + "('keychain', 14)\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter the price of hat: 2\n", + "Enter the price of mug: 4\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Total price of products are: 6.0\n" + ] + }, + { + "data": { + "text/plain": [ + "6.0" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Step A: Update the inventory quantities based on customer orders\n", + "update_inventory(customer_orders, inventory)\n", + "\n", + "# Step B: Calculate order statistics\n", + "order_status = calculate_order_statistics(customer_orders, products)\n", + "\n", + "# Step C: Print order statistics\n", + "print_order_statistics(order_status)\n", + "\n", + "# Step D: Print the updated inventory details\n", + "print_updated_inventory(inventory)\n", + "\n", + "# Step E: Calculate and print the total price (using your enhanced total_price function with error handling)\n", + "total_price(customer_orders)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cccf40b3-b5f8-4d43-8a25-7d84cfa5a365", + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "Python [conda env:base] *", "language": "python", - "name": "python3" + "name": "conda-base-py" }, "language_info": { "codemirror_mode": { @@ -90,7 +307,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.13.9" } }, "nbformat": 4,