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..26f1ab1 --- /dev/null +++ b/.ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb @@ -0,0 +1,302 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e", + "metadata": {}, + "source": [ + "# Lab | Error Handling" + ] + }, + { + "cell_type": "markdown", + "id": "6f8e446f-16b4-4e21-92e7-9d3d1eb551b6", + "metadata": {}, + "source": [ + "Objective: Practice how to identify, handle and recover from potential errors in Python code using try-except blocks." + ] + }, + { + "cell_type": "markdown", + "id": "e253e768-aed8-4791-a800-87add1204afa", + "metadata": {}, + "source": [ + "## Challenge \n", + "\n", + "Paste here your lab *functions* solutions. Apply error handling techniques to each function using try-except blocks. " + ] + }, + { + "cell_type": "markdown", + "id": "9180ff86-c3fe-4152-a609-081a287fa1af", + "metadata": {}, + "source": [ + "The try-except block in Python is designed to handle exceptions and provide a fallback mechanism when code encounters errors. By enclosing the code that could potentially throw errors in a try block, followed by specific or general exception handling in the except block, we can gracefully recover from errors and continue program execution.\n", + "\n", + "However, there may be cases where an input may not produce an immediate error, but still needs to be addressed. In such situations, it can be useful to explicitly raise an error using the \"raise\" keyword, either to draw attention to the issue or handle it elsewhere in the program.\n", + "\n", + "Modify the code to handle possible errors in Python, it is recommended to use `try-except-else-finally` blocks, incorporate the `raise` keyword where necessary, and print meaningful error messages to alert users of any issues that may occur during program execution.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "cc2c441d-9dcf-4817-b097-cf6cbe440846", + "metadata": {}, + "outputs": [], + "source": [ + "# -------------------------------------------\n", + "# Challenge: Error Handling for Lab Functions\n", + "# -------------------------------------------\n", + "\n", + "# 1. initialize_inventory\n", + "def initialize_inventory(products):\n", + " inventory = {}\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " quantity = input(f\"Enter the quantity of {product}s available: \")\n", + "\n", + " # Try converting to integer\n", + " quantity = int(quantity)\n", + "\n", + " # Raise custom error\n", + " if quantity < 0:\n", + " raise ValueError(\"Quantity cannot be negative.\")\n", + "\n", + " except ValueError as error:\n", + " print(f\"❌ Error: {error}. Please enter a valid non-negative number.\")\n", + " else:\n", + " # Executes only if no error occurred\n", + " inventory[product] = quantity\n", + " break\n", + " finally:\n", + " pass # You could log attempts here\n", + "\n", + " return inventory\n", + "\n", + "\n", + "\n", + "# 2. calculate_total_price\n", + "def calculate_total_price(products):\n", + " prices = {}\n", + "\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " price = input(f\"Enter the price for {product}: \")\n", + "\n", + " # Convert to float\n", + " price = float(price)\n", + "\n", + " # Validate\n", + " if price < 0:\n", + " raise ValueError(\"Price cannot be negative.\")\n", + "\n", + " except ValueError as error:\n", + " print(f\"❌ Error: {error}. Please enter a valid non-negative number.\")\n", + " else:\n", + " prices[product] = price\n", + " break\n", + " finally:\n", + " pass\n", + "\n", + " return prices\n", + "\n", + "\n", + "\n", + "# 3. get_customer_orders\n", + "def get_customer_orders(inventory):\n", + " # First ask for number of orders\n", + " while True:\n", + " try:\n", + " num_orders = input(\"How many orders does the customer want to place? \")\n", + " num_orders = int(num_orders)\n", + " if num_orders < 0:\n", + " raise ValueError(\"Number of orders cannot be negative.\")\n", + " except ValueError as error:\n", + " print(f\"❌ Error: {error}. Please enter a valid integer.\")\n", + " else:\n", + " break\n", + " finally:\n", + " pass\n", + "\n", + " orders = []\n", + "\n", + " for i in range(num_orders):\n", + " while True:\n", + " try:\n", + " product = input(f\"Enter product name for order {i+1}: \").strip().lower()\n", + "\n", + " # Validate product name\n", + " if product not in inventory:\n", + " raise KeyError(f\"'{product}' is not in inventory.\")\n", + "\n", + " # Validate stock\n", + " if inventory[product] == 0:\n", + " raise ValueError(f\"'{product}' is out of stock.\")\n", + "\n", + " except KeyError as key_error:\n", + " print(f\"❌ Error: {key_error}. Please enter a valid product name.\")\n", + " except ValueError as value_error:\n", + " print(f\"❌ Error: {value_error} Please choose another product.\")\n", + " else:\n", + " orders.append(product)\n", + " inventory[product] -= 1\n", + " break\n", + " finally:\n", + " pass\n", + "\n", + " return orders\n", + "\n", + "\n", + "\n", + "# 4. Main program to test everything\n", + "def main():\n", + " products = [\"apple\", \"banana\", \"orange\"]\n", + "\n", + " print(\"\\n--- Initialize Inventory ---\")\n", + " inventory = initialize_inventory(products)\n", + "\n", + " print(\"\\n--- Set Product Prices ---\")\n", + " prices = calculate_total_price(products)\n", + "\n", + " print(\"\\n--- Customer Orders ---\")\n", + " orders = get_customer_orders(inventory)\n", + "\n", + " print(\"\\nFinal Orders:\", orders)\n", + " print(\"Remaining Inventory:\", inventory)\n", + " print(\"Prices:\", prices)\n", + "\n", + "\n", + "# Run program\n", + "# main()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "e909c1d3-bc90-4950-99e6-0b13bab816e6", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- Initialize Inventory ---\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter the quantity of apples available: 15\n", + "Enter the quantity of bananas available: 10\n", + "Enter the quantity of oranges available: 8\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- Set Product Prices ---\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter the price for apple: 150\n", + "Enter the price for banana: 100\n", + "Enter the price for orange: 200\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- Customer Orders ---\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "How many orders does the customer want to place? apple\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "❌ Error: invalid literal for int() with base 10: 'apple'. Please enter a valid integer.\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "How many orders does the customer want to place? 10\n", + "Enter product name for order 1: apple\n", + "Enter product name for order 2: banana\n", + "Enter product name for order 3: orange\n", + "Enter product name for order 4: orange\n", + "Enter product name for order 5: banana\n", + "Enter product name for order 6: apple\n", + "Enter product name for order 7: orange\n", + "Enter product name for order 8: apple\n", + "Enter product name for order 9: banana\n", + "Enter product name for order 10: orange\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Final Orders: ['apple', 'banana', 'orange', 'orange', 'banana', 'apple', 'orange', 'apple', 'banana', 'orange']\n", + "Remaining Inventory: {'apple': 12, 'banana': 7, 'orange': 4}\n", + "Prices: {'apple': 150.0, 'banana': 100.0, 'orange': 200.0}\n" + ] + } + ], + "source": [ + "main()\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c10d7370-8f04-4303-a43c-50aab34170ba", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index 3e50ef8..b7e6aed 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -41,13 +41,392 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "id": "cc2c441d-9dcf-4817-b097-cf6cbe440846", "metadata": {}, "outputs": [], "source": [ - "# your code goes here" + "# -------------------------------------------\n", + "# Challenge: Error Handling for Lab Functions\n", + "# -------------------------------------------\n", + "\n", + "# 1. initialize_inventory\n", + "def initialize_inventory(products):\n", + " inventory = {}\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " quantity = input(f\"Enter the quantity of {product}s available: \")\n", + "\n", + " # Try converting to integer\n", + " quantity = int(quantity)\n", + "\n", + " # Raise custom error\n", + " if quantity < 0:\n", + " raise ValueError(\"Quantity cannot be negative.\")\n", + "\n", + " except ValueError as error:\n", + " print(f\"❌ Error: {error}. Please enter a valid non-negative number.\")\n", + " else:\n", + " # Executes only if no error occurred\n", + " inventory[product] = quantity\n", + " break\n", + " finally:\n", + " pass # You could log attempts here\n", + "\n", + " return inventory\n", + "\n", + "\n", + "\n", + "# 2. calculate_total_price\n", + "def calculate_total_price(products):\n", + " prices = {}\n", + "\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " price = input(f\"Enter the price for {product}: \")\n", + "\n", + " # Convert to float\n", + " price = float(price)\n", + "\n", + " # Validate\n", + " if price < 0:\n", + " raise ValueError(\"Price cannot be negative.\")\n", + "\n", + " except ValueError as error:\n", + " print(f\"❌ Error: {error}. Please enter a valid non-negative number.\")\n", + " else:\n", + " prices[product] = price\n", + " break\n", + " finally:\n", + " pass\n", + "\n", + " return prices\n", + "\n", + "\n", + "\n", + "# 3. get_customer_orders\n", + "def get_customer_orders(inventory):\n", + " # First ask for number of orders\n", + " while True:\n", + " try:\n", + " num_orders = input(\"How many orders does the customer want to place? \")\n", + " num_orders = int(num_orders)\n", + " if num_orders < 0:\n", + " raise ValueError(\"Number of orders cannot be negative.\")\n", + " except ValueError as error:\n", + " print(f\"❌ Error: {error}. Please enter a valid integer.\")\n", + " else:\n", + " break\n", + " finally:\n", + " pass\n", + "\n", + " orders = []\n", + "\n", + " for i in range(num_orders):\n", + " while True:\n", + " try:\n", + " product = input(f\"Enter product name for order {i+1}: \").strip().lower()\n", + "\n", + " # Validate product name\n", + " if product not in inventory:\n", + " raise KeyError(f\"'{product}' is not in inventory.\")\n", + "\n", + " # Validate stock\n", + " if inventory[product] == 0:\n", + " raise ValueError(f\"'{product}' is out of stock.\")\n", + "\n", + " except KeyError as key_error:\n", + " print(f\"❌ Error: {key_error}. Please enter a valid product name.\")\n", + " except ValueError as value_error:\n", + " print(f\"❌ Error: {value_error} Please choose another product.\")\n", + " else:\n", + " orders.append(product)\n", + " inventory[product] -= 1\n", + " break\n", + " finally:\n", + " pass\n", + "\n", + " return orders\n", + "\n", + "\n", + "\n", + "# 4. Main program to test everything\n", + "def main():\n", + " products = [\"apple\", \"banana\", \"orange\"]\n", + "\n", + " print(\"\\n--- Initialize Inventory ---\")\n", + " inventory = initialize_inventory(products)\n", + "\n", + " print(\"\\n--- Set Product Prices ---\")\n", + " prices = calculate_total_price(products)\n", + "\n", + " print(\"\\n--- Customer Orders ---\")\n", + " orders = get_customer_orders(inventory)\n", + "\n", + " print(\"\\nFinal Orders:\", orders)\n", + " print(\"Remaining Inventory:\", inventory)\n", + " print(\"Prices:\", prices)\n", + "\n", + "\n", + "# Run program\n", + "# main()\n" ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "e909c1d3-bc90-4950-99e6-0b13bab816e6", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- Initialize Inventory ---\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter the quantity of apples available: 15\n", + "Enter the quantity of bananas available: 10\n", + "Enter the quantity of oranges available: 8\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- Set Product Prices ---\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter the price for apple: 150\n", + "Enter the price for banana: 100\n", + "Enter the price for orange: 200\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- Customer Orders ---\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "How many orders does the customer want to place? apple\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "❌ Error: invalid literal for int() with base 10: 'apple'. Please enter a valid integer.\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "How many orders does the customer want to place? 10\n", + "Enter product name for order 1: apple\n", + "Enter product name for order 2: banana\n", + "Enter product name for order 3: orange\n", + "Enter product name for order 4: orange\n", + "Enter product name for order 5: banana\n", + "Enter product name for order 6: apple\n", + "Enter product name for order 7: orange\n", + "Enter product name for order 8: apple\n", + "Enter product name for order 9: banana\n", + "Enter product name for order 10: orange\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Final Orders: ['apple', 'banana', 'orange', 'orange', 'banana', 'apple', 'orange', 'apple', 'banana', 'orange']\n", + "Remaining Inventory: {'apple': 12, 'banana': 7, 'orange': 4}\n", + "Prices: {'apple': 150.0, 'banana': 100.0, 'orange': 200.0}\n" + ] + } + ], + "source": [ + "main()\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "c10d7370-8f04-4303-a43c-50aab34170ba", + "metadata": {}, + "outputs": [], + "source": [ + "import string\n", + "\n", + "# 1. Unique list with error handling\n", + "def get_unique_list(values):\n", + " try:\n", + " if not isinstance(values, list):\n", + " raise TypeError(\"Input must be a list.\")\n", + " return list(set(values))\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return []\n", + "\n", + "# 2. Count upper & lower case\n", + "def count_case(text):\n", + " try:\n", + " if not isinstance(text, str):\n", + " raise TypeError(\"Input must be a string.\")\n", + " upper_count = sum(1 for c in text if c.isupper())\n", + " lower_count = sum(1 for c in text if c.islower())\n", + " return {\"upper\": upper_count, \"lower\": lower_count}\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return None\n", + "\n", + "# 3. Remove punctuation\n", + "def remove_punctuation(text):\n", + " try:\n", + " if not isinstance(text, str):\n", + " raise TypeError(\"Input must be a string.\")\n", + " return text.translate(str.maketrans('', '', string.punctuation))\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return \"\"\n", + "\n", + "# 4. Word count with error handling\n", + "def word_count(text):\n", + " try:\n", + " if not isinstance(text, str):\n", + " raise TypeError(\"Input must be a string.\")\n", + " clean_text = remove_punctuation(text)\n", + " words = clean_text.split()\n", + " return len(words)\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return 0\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "ccc34a3a-9095-40d7-bbee-8af653873971", + "metadata": {}, + "outputs": [], + "source": [ + "# Calculator operations\n", + "def add(*nums):\n", + " try:\n", + " return sum(float(n) for n in nums)\n", + " except Exception:\n", + " raise ValueError(\"All inputs must be numbers.\")\n", + "\n", + "def subtract(*nums):\n", + " try:\n", + " nums = [float(n) for n in nums]\n", + " result = nums[0]\n", + " for n in nums[1:]:\n", + " result -= n\n", + " return result\n", + " except Exception:\n", + " raise ValueError(\"All inputs must be numbers.\")\n", + "\n", + "def multiply(*nums):\n", + " try:\n", + " nums = [float(n) for n in nums]\n", + " result = 1\n", + " for n in nums:\n", + " result *= n\n", + " return result\n", + " except Exception:\n", + " raise ValueError(\"All inputs must be numbers.\")\n", + "\n", + "def divide(*nums):\n", + " try:\n", + " nums = [float(n) for n in nums]\n", + " result = nums[0]\n", + " for n in nums[1:]:\n", + " if n == 0:\n", + " raise ZeroDivisionError(\"Cannot divide by zero.\")\n", + " result /= n\n", + " return result\n", + " except ZeroDivisionError as e:\n", + " print(f\"Error: {e}\")\n", + " except Exception:\n", + " raise ValueError(\"All inputs must be numbers.\")\n", + "\n", + "# Operator handler\n", + "def calculator(operator, *nums):\n", + " try:\n", + " if operator == '+':\n", + " return add(*nums)\n", + " elif operator == '-':\n", + " return subtract(*nums)\n", + " elif operator == '*':\n", + " return multiply(*nums)\n", + " elif operator == '/':\n", + " return divide(*nums)\n", + " else:\n", + " raise ValueError(\"Invalid operator. Use +, -, *, or /.\")\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return None\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "16ce4ae9-a833-4a1f-9443-dc80d8bcb281", + "metadata": {}, + "outputs": [], + "source": [ + "def fibonacci(n):\n", + " try:\n", + " if not isinstance(n, int):\n", + " raise TypeError(\"Input must be an integer.\")\n", + " if n < 0:\n", + " raise ValueError(\"Input must be non-negative.\")\n", + " if n in (0, 1):\n", + " return n\n", + " return fibonacci(n-1) + fibonacci(n-2)\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + "\n", + "def fibonacci_sequence(n):\n", + " try:\n", + " if not isinstance(n, int):\n", + " raise TypeError(\"Input must be an integer.\")\n", + " if n < 0:\n", + " raise ValueError(\"Input must be non-negative.\")\n", + " return [fibonacci(i) for i in range(n)]\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return []\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b470182e-3f17-48ba-9dbc-db1beb8d3c4c", + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { @@ -66,7 +445,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.13.6" } }, "nbformat": 4,