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..3e31ae7 --- /dev/null +++ b/.ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb @@ -0,0 +1,203 @@ +{ + "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": 1, + "id": "485dbd73-1eb0-4d45-9004-0164de722a35", + "metadata": {}, + "outputs": [], + "source": [ + "def calculate_total_price(products):\n", + " total_price = 0\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " # Prompt user to enter price for the product\n", + " price = float(input(f\"Enter the price for {product}: \"))\n", + " # Check if price is negative\n", + " if price < 0:\n", + " print(\"Price cannot be negative. Please enter a valid price.\")\n", + " continue\n", + " # Add price to total\n", + " total_price += price\n", + " break # Exit the loop if input is valid\n", + " except ValueError:\n", + " print(\"Invalid input. Please enter a numeric price.\") # Handle non-numeric input\n", + " return total_price" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "06470ce5-603a-4503-a987-ba0263aa6254", + "metadata": {}, + "outputs": [], + "source": [ + "def get_customer_orders(inventory):\n", + " orders = {}\n", + "\n", + " # Ask for number of orders with input validation\n", + " while True:\n", + " try:\n", + " num_orders = int(input(\"Enter number of orders: \"))\n", + " if num_orders < 0:\n", + " print(\"Number of orders cannot be negative. Please enter again.\")\n", + " continue\n", + " break\n", + " except ValueError:\n", + " print(\"Invalid input. Please enter a valid integer.\")\n", + "\n", + " # For each order, ask for product and quantity with validation\n", + " for _ in range(num_orders):\n", + " while True:\n", + " product = input(\"Enter product name: \")\n", + " # Check if product exists in inventory\n", + " if product not in inventory:\n", + " print(f\"Product '{product}' not found in inventory. Please enter a valid product.\")\n", + " continue\n", + " # Check if product is in stock\n", + " if inventory[product] <= 0:\n", + " print(f\"Sorry, '{product}' is out of stock. Choose another product.\")\n", + " continue\n", + " break\n", + "\n", + " while True:\n", + " try:\n", + " quantity = int(input(f\"Enter quantity of {product}: \"))\n", + " # Quantity must be positive\n", + " if quantity <= 0:\n", + " print(\"Quantity must be positive.\")\n", + " continue\n", + " # Quantity must not exceed stock\n", + " if quantity > inventory[product]:\n", + " print(f\"Only {inventory[product]} {product}(s) available. Enter a smaller quantity.\")\n", + " continue\n", + " break\n", + " except ValueError:\n", + " print(\"Invalid input. Please enter a valid quantity.\")\n", + "\n", + " # Record the order and update inventory\n", + " orders[product] = orders.get(product, 0) + quantity\n", + " inventory[product] -= quantity\n", + "\n", + " return orders" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ac80763-c23e-4a4f-9215-65e8b9838f13", + "metadata": {}, + "outputs": [], + "source": [ + "products = ['apple', 'banana', 'orange']\n", + "\n", + "# Initialize inventory (using your error-handling function)\n", + "inventory = initialize_inventory(products)\n", + "\n", + "# Get customer orders with validation\n", + "orders = get_customer_orders(inventory)\n", + "\n", + "# Calculate total price for ordered products\n", + "total_price = calculate_total_price(list(orders.keys()))\n", + "\n", + "print(\"Orders:\", orders)\n", + "print(\"Total price:\", total_price)" + ] + } + ], + "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.13.3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index f4c6ef6..3e31ae7 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -72,6 +72,111 @@ "\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": 1, + "id": "485dbd73-1eb0-4d45-9004-0164de722a35", + "metadata": {}, + "outputs": [], + "source": [ + "def calculate_total_price(products):\n", + " total_price = 0\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " # Prompt user to enter price for the product\n", + " price = float(input(f\"Enter the price for {product}: \"))\n", + " # Check if price is negative\n", + " if price < 0:\n", + " print(\"Price cannot be negative. Please enter a valid price.\")\n", + " continue\n", + " # Add price to total\n", + " total_price += price\n", + " break # Exit the loop if input is valid\n", + " except ValueError:\n", + " print(\"Invalid input. Please enter a numeric price.\") # Handle non-numeric input\n", + " return total_price" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "06470ce5-603a-4503-a987-ba0263aa6254", + "metadata": {}, + "outputs": [], + "source": [ + "def get_customer_orders(inventory):\n", + " orders = {}\n", + "\n", + " # Ask for number of orders with input validation\n", + " while True:\n", + " try:\n", + " num_orders = int(input(\"Enter number of orders: \"))\n", + " if num_orders < 0:\n", + " print(\"Number of orders cannot be negative. Please enter again.\")\n", + " continue\n", + " break\n", + " except ValueError:\n", + " print(\"Invalid input. Please enter a valid integer.\")\n", + "\n", + " # For each order, ask for product and quantity with validation\n", + " for _ in range(num_orders):\n", + " while True:\n", + " product = input(\"Enter product name: \")\n", + " # Check if product exists in inventory\n", + " if product not in inventory:\n", + " print(f\"Product '{product}' not found in inventory. Please enter a valid product.\")\n", + " continue\n", + " # Check if product is in stock\n", + " if inventory[product] <= 0:\n", + " print(f\"Sorry, '{product}' is out of stock. Choose another product.\")\n", + " continue\n", + " break\n", + "\n", + " while True:\n", + " try:\n", + " quantity = int(input(f\"Enter quantity of {product}: \"))\n", + " # Quantity must be positive\n", + " if quantity <= 0:\n", + " print(\"Quantity must be positive.\")\n", + " continue\n", + " # Quantity must not exceed stock\n", + " if quantity > inventory[product]:\n", + " print(f\"Only {inventory[product]} {product}(s) available. Enter a smaller quantity.\")\n", + " continue\n", + " break\n", + " except ValueError:\n", + " print(\"Invalid input. Please enter a valid quantity.\")\n", + "\n", + " # Record the order and update inventory\n", + " orders[product] = orders.get(product, 0) + quantity\n", + " inventory[product] -= quantity\n", + "\n", + " return orders" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ac80763-c23e-4a4f-9215-65e8b9838f13", + "metadata": {}, + "outputs": [], + "source": [ + "products = ['apple', 'banana', 'orange']\n", + "\n", + "# Initialize inventory (using your error-handling function)\n", + "inventory = initialize_inventory(products)\n", + "\n", + "# Get customer orders with validation\n", + "orders = get_customer_orders(inventory)\n", + "\n", + "# Calculate total price for ordered products\n", + "total_price = calculate_total_price(list(orders.keys()))\n", + "\n", + "print(\"Orders:\", orders)\n", + "print(\"Total price:\", total_price)" + ] } ], "metadata": { @@ -90,7 +195,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.13.3" } }, "nbformat": 4,