Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
262 changes: 262 additions & 0 deletions .ipynb_checkpoints/lab-python-error-handling-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -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
}
Loading