Skip to content

Instantly share code, notes, and snippets.

@A1isone
Created May 16, 2021 15:34
Show Gist options
  • Save A1isone/990483482b1b88a395f47260eb457ab3 to your computer and use it in GitHub Desktop.
Save A1isone/990483482b1b88a395f47260eb457ab3 to your computer and use it in GitHub Desktop.
C2M5L4_Errors_and_Exceptions-V2.json
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Practice Notebook - Errors and Exceptions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below we have a function that removes an item from an input list. Run it to see what it does."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[5, 9, 6, 8]\n"
]
}
],
"source": [
"my_list = [27, 5, 9, 6, 8]\n",
"\n",
"def RemoveValue(myVal):\n",
" my_list.remove(myVal)\n",
" return my_list\n",
"\n",
"print(RemoveValue(27))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We used the `RemoveValue()` function to remove the number, 27 from the given list. Great! The function seems to be working fine. However, there is a problem when we try to call the function on the number 27 again. Run the following cell to see what happens. "
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"ename": "ValueError",
"evalue": "list.remove(x): x not in list",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-3-3f8c37f416f6>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mRemoveValue\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m27\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-2-597531fc6dcc>\u001b[0m in \u001b[0;36mRemoveValue\u001b[0;34m(myVal)\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mRemoveValue\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmyVal\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mmy_list\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mremove\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmyVal\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mmy_list\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mValueError\u001b[0m: list.remove(x): x not in list"
]
}
],
"source": [
"print(RemoveValue(27))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From the above output we see that our function now raises a <font color=red>**ValueError**</font>. This is because we are trying to remove a number from a list that is not in the list. When we removed 27 from the list the first time, it was no longer available in the list to be removed a second time. Python is letting us know that the number 27 no longer makes sense for our `RemoveValue()` function. \n",
"<br><br>\n",
"We'd like to take control of the error messaging here and pre-empt this error. Fill in the blanks below to raise a ValueError in the `RemoveValue()` function if a value is not in the list. You can have the error message say something obvious like \"Value must be in the given list\"."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"def RemoveValue(myVal):\n",
" if myVal not in my_list:\n",
" return None\n",
" else:\n",
" my_list.remove(myVal)\n",
" return my_list\n",
"\n",
"print(RemoveValue(27))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Did your error message print correctly? Was the output something like: **<font color=red>ValueError:</font> Value must be in the given list**? If not, go back to the previous cell and make sure you filled in the blanks correctly. If your error message did print correctly, great! You are on your way to mastering the basics of handling errors and exceptions.\n",
"<br><br>\n",
"Now, let's look at a different function. Below we have a function that sorts an input list alphabetically. Run it to see what it does."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['after', 'east', 'inside', 'over', 'up']\n"
]
}
],
"source": [
"my_word_list = ['east', 'after', 'up', 'over', 'inside']\n",
"\n",
"def OrganizeList(myList):\n",
" myList.sort()\n",
" return myList\n",
"\n",
"print(OrganizeList(my_word_list))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We used the `OrganizeList()` function to sort a given list alphabetically. The function seems to be working fine. However, there is a problem when we try to call the function on a list containing number values. Run the following cell to see what happens."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "'<' not supported between instances of 'str' and 'int'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-6-459d95f39adf>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mmy_new_list\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m6\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m8\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"12\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m42\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mOrganizeList\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmy_new_list\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-5-252da45e411d>\u001b[0m in \u001b[0;36mOrganizeList\u001b[0;34m(myList)\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mOrganizeList\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmyList\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mmyList\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msort\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mmyList\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mTypeError\u001b[0m: '<' not supported between instances of 'str' and 'int'"
]
}
],
"source": [
"my_new_list = [6, 3, 8, \"12\", 42]\n",
"print(OrganizeList(my_new_list))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From the above output we see that our function now raises a <font color=red>**TypeError**</font>. This is because the `OrganizeList()` function makes sense for lists that are filled with only strings. Take control of the error messaging here and pre-empt this error by filling in the blanks below to add an assert type argument that verifies whether the input list is filled with only strings. You can have the error message say something like \"Word list must be a list of strings\"."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"ename": "AssertionError",
"evalue": "",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-8-c65c942f806a>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mmyList\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mOrganizeList\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmy_new_list\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-8-c65c942f806a>\u001b[0m in \u001b[0;36mOrganizeList\u001b[0;34m(myList)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mOrganizeList\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmyList\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mitem\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mmyList\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mAssertionError\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mmyList\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msort\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mmyList\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mAssertionError\u001b[0m: "
]
}
],
"source": [
"def OrganizeList(myList):\n",
" for item in myList:\n",
" if not str(): raise AssertionError\n",
" myList.sort()\n",
" return myList\n",
"\n",
"print(OrganizeList(my_new_list))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Did your error message print correctly? Was the output something like: **<font color=red>AssertionError:</font> Word list must be a list of strings**? If not, go back to the previous cell and make sure you filled in the blanks correctly. If your error message did print correctly, excellent! You are another step closer to mastering the basics of handling errors and exceptions.\n",
"<br><br>\n",
"Let's look at one last code block. The `Guess()` function below takes a list of participants, assigns each a random number from 1 to 9, and stores this information in a dictionary with the participant name as the key. It then returns *True* if Larry was assigned the number 9 and *False* if this was not the case. Run it to see what it does."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n"
]
}
],
"source": [
"import random\n",
"\n",
"participants = ['Jack','Jill','Larry','Tom']\n",
"\n",
"def Guess(participants):\n",
" my_participant_dict = {}\n",
" for participant in participants:\n",
" my_participant_dict[participant] = random.randint(1, 9)\n",
" if my_participant_dict['Larry'] == 9:\n",
" return True\n",
" else:\n",
" return False\n",
" \n",
"print(Guess(participants))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code seems to be working fine. However, there are some things that could go wrong, so find the part that might throw an exception and wrap it in a try-except block to ensure that you get sensible behavior. Do this in the cell below. Code your function to return *None* if an exception occurs."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"# Revised Guess() function\n",
"def Guess(participants):\n",
" my_participant_dict = {}\n",
" for participant in participants:\n",
" my_participant_dict[participant] = random.randint(1, 9)\n",
" try:\n",
" if my_participant_dict['Larry'] == 9:\n",
" return True\n",
" else:\n",
" return False\n",
" except:\n",
" return None"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Call your revised `Guess()` function with the following participant list."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"participants = ['Cathy','Fred','Jack','Tom']\n",
"print(Guess(participants))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Was the above output *None*? If not, go back to the code block containing your revised `Guess()` function and make edits so that the output is *None* for the previous code block. If the above output was indeed *None*, congratulations! You've mastered the basics of handling errors and exceptions in Python and you are all done with this notebook!"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.6.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment