From dd45a1f21e76f449fb25429c3ec4dfc6eb4d7e0d Mon Sep 17 00:00:00 2001 From: Egbe Grace Date: Thu, 24 Jul 2025 00:11:23 +0200 Subject: [PATCH] Refactored lab functions with try-except, raise, and error handling --- ...lab-python-error-handling-checkpoint.ipynb | 262 ++++++++++++++++++ lab-python-error-handling.ipynb | 198 ++++++++++++- 2 files changed, 455 insertions(+), 5 deletions(-) create mode 100644 .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb 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..b60eb7d --- /dev/null +++ b/.ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb @@ -0,0 +1,262 @@ +{ + "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": "9564c3d1-9510-4dde-9464-9ac08d3af0cd", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " Finished get_unique_list.\n", + "[1, 2, 3]\n", + "Error: Input must be a list.\n", + " Finished get_unique_list.\n", + "[]\n" + ] + } + ], + "source": [ + "def get_unique_list(lst):\n", + " try:\n", + " if not isinstance(lst, list):\n", + " raise TypeError(\"Input must be a list.\")\n", + " unique = []\n", + " for item in lst:\n", + " if item not in unique:\n", + " unique.append(item)\n", + " except TypeError as e:\n", + " print(f\"Error: {e}\")\n", + " return []\n", + " else:\n", + " return unique\n", + " finally:\n", + " print(\" Finished get_unique_list.\")\n", + " \n", + "# Tests\n", + "print(get_unique_list([1, 2, 2, 3]))\n", + "print(get_unique_list(\"123\")) # error\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "0c303130-4bbc-49b7-842d-b9b64ce55cf7", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " Finished count_case.\n", + "(2, 8)\n", + "Error: Input must be a string.\n", + " Finished count_case.\n", + "(0, 0)\n" + ] + } + ], + "source": [ + "def count_case(string):\n", + " try:\n", + " if not isinstance(string, str):\n", + " raise TypeError(\"Input must be a string.\")\n", + " upper = sum(1 for c in string if c.isupper())\n", + " lower = sum(1 for c in string if c.islower())\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return (0, 0)\n", + " else:\n", + " return (upper, lower)\n", + " finally:\n", + " print(\" Finished count_case.\")\n", + " \n", + "# Tests\n", + "print(count_case(\"Hello World\"))\n", + "print(count_case(12345)) # error\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "99b35007-e1e3-4d5c-b6e5-46bc4cc34e72", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello world\n", + "Error: Input must be a string.\n", + "\n" + ] + } + ], + "source": [ + "import string\n", + "\n", + "def remove_punctuation(sentence):\n", + " try:\n", + " if not isinstance(sentence, str):\n", + " raise TypeError(\"Input must be a string.\")\n", + " return sentence.translate(str.maketrans('', '', string.punctuation))\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return \"\"\n", + " \n", + "# Tests\n", + "print(remove_punctuation(\"Hello, world!\"))\n", + "print(remove_punctuation(123)) # error\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "164c3a42-1900-4f10-9efc-4731e9837078", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n", + "Error: Input must be a string.\n", + "0\n" + ] + } + ], + "source": [ + "def word_count(sentence):\n", + " try:\n", + " clean_sentence = remove_punctuation(sentence)\n", + " words = clean_sentence.split()\n", + " return len(words)\n", + " except Exception as e:\n", + " print(f\"Error counting words: {e}\")\n", + " return 0\n", + " \n", + "# Tests\n", + "print(word_count(\"This is, a test!\"))\n", + "print(word_count(12345)) # error\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "e79b87ac-3b82-4457-9e42-0c44b1754dc1", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " Finished calculate.\n", + "15\n", + "Error during calculation: Cannot divide by zero.\n", + " Finished calculate.\n", + "None\n", + "Error during calculation: Invalid operator. Use one of +, -, *, /.\n", + " Finished calculate.\n", + "None\n" + ] + } + ], + "source": [ + "def calculate(a, b, operator):\n", + " try:\n", + " if operator == '+':\n", + " return a + b\n", + " elif operator == '-':\n", + " return a - b\n", + " elif operator == '*':\n", + " return a * b\n", + " elif operator == '/':\n", + " if b == 0:\n", + " raise ZeroDivisionError(\"Cannot divide by zero.\")\n", + " return a / b\n", + " else:\n", + " raise ValueError(\"Invalid operator. Use one of +, -, *, /.\")\n", + " except Exception as e:\n", + " print(f\"Error during calculation: {e}\")\n", + " return None\n", + " finally:\n", + " print(\" Finished calculate.\")\n", + " \n", + "# Tests\n", + "print(calculate(10, 5, '+'))\n", + "print(calculate(10, 0, '/')) # divide by zero\n", + "print(calculate(10, 2, '%')) # invalid operator\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3f29ac24-8e2b-488f-a6ec-c65355a611f7", + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index 3e50ef8..b60eb7d 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -41,13 +41,201 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "cc2c441d-9dcf-4817-b097-cf6cbe440846", + "execution_count": 2, + "id": "9564c3d1-9510-4dde-9464-9ac08d3af0cd", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " Finished get_unique_list.\n", + "[1, 2, 3]\n", + "Error: Input must be a list.\n", + " Finished get_unique_list.\n", + "[]\n" + ] + } + ], "source": [ - "# your code goes here" + "def get_unique_list(lst):\n", + " try:\n", + " if not isinstance(lst, list):\n", + " raise TypeError(\"Input must be a list.\")\n", + " unique = []\n", + " for item in lst:\n", + " if item not in unique:\n", + " unique.append(item)\n", + " except TypeError as e:\n", + " print(f\"Error: {e}\")\n", + " return []\n", + " else:\n", + " return unique\n", + " finally:\n", + " print(\" Finished get_unique_list.\")\n", + " \n", + "# Tests\n", + "print(get_unique_list([1, 2, 2, 3]))\n", + "print(get_unique_list(\"123\")) # error\n" ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "0c303130-4bbc-49b7-842d-b9b64ce55cf7", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " Finished count_case.\n", + "(2, 8)\n", + "Error: Input must be a string.\n", + " Finished count_case.\n", + "(0, 0)\n" + ] + } + ], + "source": [ + "def count_case(string):\n", + " try:\n", + " if not isinstance(string, str):\n", + " raise TypeError(\"Input must be a string.\")\n", + " upper = sum(1 for c in string if c.isupper())\n", + " lower = sum(1 for c in string if c.islower())\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return (0, 0)\n", + " else:\n", + " return (upper, lower)\n", + " finally:\n", + " print(\" Finished count_case.\")\n", + " \n", + "# Tests\n", + "print(count_case(\"Hello World\"))\n", + "print(count_case(12345)) # error\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "99b35007-e1e3-4d5c-b6e5-46bc4cc34e72", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello world\n", + "Error: Input must be a string.\n", + "\n" + ] + } + ], + "source": [ + "import string\n", + "\n", + "def remove_punctuation(sentence):\n", + " try:\n", + " if not isinstance(sentence, str):\n", + " raise TypeError(\"Input must be a string.\")\n", + " return sentence.translate(str.maketrans('', '', string.punctuation))\n", + " except Exception as e:\n", + " print(f\"Error: {e}\")\n", + " return \"\"\n", + " \n", + "# Tests\n", + "print(remove_punctuation(\"Hello, world!\"))\n", + "print(remove_punctuation(123)) # error\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "164c3a42-1900-4f10-9efc-4731e9837078", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n", + "Error: Input must be a string.\n", + "0\n" + ] + } + ], + "source": [ + "def word_count(sentence):\n", + " try:\n", + " clean_sentence = remove_punctuation(sentence)\n", + " words = clean_sentence.split()\n", + " return len(words)\n", + " except Exception as e:\n", + " print(f\"Error counting words: {e}\")\n", + " return 0\n", + " \n", + "# Tests\n", + "print(word_count(\"This is, a test!\"))\n", + "print(word_count(12345)) # error\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "e79b87ac-3b82-4457-9e42-0c44b1754dc1", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " Finished calculate.\n", + "15\n", + "Error during calculation: Cannot divide by zero.\n", + " Finished calculate.\n", + "None\n", + "Error during calculation: Invalid operator. Use one of +, -, *, /.\n", + " Finished calculate.\n", + "None\n" + ] + } + ], + "source": [ + "def calculate(a, b, operator):\n", + " try:\n", + " if operator == '+':\n", + " return a + b\n", + " elif operator == '-':\n", + " return a - b\n", + " elif operator == '*':\n", + " return a * b\n", + " elif operator == '/':\n", + " if b == 0:\n", + " raise ZeroDivisionError(\"Cannot divide by zero.\")\n", + " return a / b\n", + " else:\n", + " raise ValueError(\"Invalid operator. Use one of +, -, *, /.\")\n", + " except Exception as e:\n", + " print(f\"Error during calculation: {e}\")\n", + " return None\n", + " finally:\n", + " print(\" Finished calculate.\")\n", + " \n", + "# Tests\n", + "print(calculate(10, 5, '+'))\n", + "print(calculate(10, 0, '/')) # divide by zero\n", + "print(calculate(10, 2, '%')) # invalid operator\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3f29ac24-8e2b-488f-a6ec-c65355a611f7", + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { @@ -66,7 +254,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.13.2" } }, "nbformat": 4,