Skip to content

Instantly share code, notes, and snippets.

@hilt329
Created April 8, 2021 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hilt329/3097e2c31ff7bfeb4d56a0db775f5d1a to your computer and use it in GitHub Desktop.
Save hilt329/3097e2c31ff7bfeb4d56a0db775f5d1a to your computer and use it in GitHub Desktop.
Created on Skills Network Labs
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<center>\n",
" <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n",
"</center>\n",
"\n",
"# Functions in Python\n",
"\n",
"Estimated time needed: **40** minutes\n",
"\n",
"## Objectives\n",
"\n",
"After completing this lab you will be able to:\n",
"\n",
"- Understand functions and variables\n",
"- Work with functions and variables\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h1>Functions in Python</h1>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<p><strong>Welcome!</strong> This notebook will teach you about the functions in the Python Programming Language. By the end of this lab, you'll know the basic concepts about function, variables, and how to use functions.</p>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2>Table of Contents</h2>\n",
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
" <ul>\n",
" <li>\n",
" <a href=\"#func\">Functions</a>\n",
" <ul>\n",
" <li><a href=\"content\">What is a function?</a></li>\n",
" <li><a href=\"var\">Variables</a></li>\n",
" <li><a href=\"simple\">Functions Make Things Simple</a></li>\n",
" </ul>\n",
" </li>\n",
" <li><a href=\"pre\">Pre-defined functions</a></li>\n",
" <li><a href=\"if\">Using <code>if</code>/<code>else</code> Statements and Loops in Functions</a></li>\n",
" <li><a href=\"default\">Setting default argument values in your custom functions</a></li>\n",
" <li><a href=\"global\">Global variables</a></li>\n",
" <li><a href=\"scope\">Scope of a Variable</a></li>\n",
" <li><a href=\"collec\">Collections and Functions</a></li>\n",
" <li>\n",
" <a href=\"#quiz\">Quiz on Loops</a>\n",
" </li>\n",
" </ul>\n",
"\n",
"</div>\n",
"\n",
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"func\">Functions</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A function is a reusable block of code which performs operations specified in the function. They let you break down tasks and allow you to reuse your code in different programs.\n",
"\n",
"There are two types of functions :\n",
"\n",
"- <b>Pre-defined functions</b>\n",
"- <b>User defined functions</b>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3 id=\"content\">What is a Function?</h3>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can define functions to provide the required functionality. Here are simple rules to define a function in Python:\n",
"\n",
"- Functions blocks begin <code>def</code> followed by the function <code>name</code> and parentheses <code>()</code>.\n",
"- There are input parameters or arguments that should be placed within these parentheses. \n",
"- You can also define parameters inside these parentheses.\n",
"- There is a body within every function that starts with a colon (<code>:</code>) and is indented.\n",
"- You can also place documentation before the body. \n",
"- The statement <code>return</code> exits a function, optionally passing back a value. \n",
"\n",
"An example of a function that adds on to the parameter <code>a</code> prints and returns the output as <code>b</code>:\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5 if you add one 6\n"
]
},
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# First function example: Add 1 to a and store as b\n",
"\n",
"def add(a):\n",
" b = a + 1\n",
" print(a, \"if you add one\", b)\n",
" return(b)\n",
"add(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The figure below illustrates the terminology: \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/images/FuncsDefinition.png\" width=\"500\" /> \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can obtain help about a function :\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on function add in module __main__:\n",
"\n",
"add(a)\n",
"\n"
]
}
],
"source": [
"# Get a help on add function\n",
"\n",
"help(add)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can call the function:\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 if you add one 2\n"
]
},
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Call the function add()\n",
"\n",
"add(1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we call the function with a new input we get a new result:\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 if you add one 3\n"
]
},
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Call the function add()\n",
"\n",
"add(2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can create different functions. For example, we can create a function that multiplies two numbers. The numbers will be represented by the variables <code>a</code> and <code>b</code>:\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"24\n"
]
}
],
"source": [
"# Define a function for multiple two numbers\n",
"\n",
"def Mult(a, b):\n",
" c = a * b\n",
" return(c)\n",
" print(\"This is not printed\")\n",
" \n",
"result = Mult(12,2)\n",
"print(result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The same function can be used for different data types. For example, we can multiply two integers:\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use mult() multiply two integers\n",
"\n",
"Mult(2, 3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note how the function terminates at the <code> return </code> statement, while passing back a value. This value can be further assigned to a different variable as desired.\n",
"\n",
"<hr>\n",
"The same function can be used for different data types. For example, we can multiply two integers:\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Two Floats: \n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"31.400000000000002"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use mult() multiply two floats\n",
"\n",
"Mult(10.0, 3.14)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can even replicate a string by multiplying with an integer: \n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Michael Jackson Michael Jackson '"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use mult() multiply two different type values together\n",
"\n",
"Mult(2, \"Michael Jackson \")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3 id=\"var\">Variables</h3>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The input to a function is called a formal parameter.\n",
"\n",
"A variable that is declared inside a function is called a local variable. The parameter only exists within the function (i.e. the point where the function starts and stops). \n",
"\n",
"A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout the program. We will discuss more about global variables at the end of the lab.\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"# Function Definition\n",
"\n",
"def square(a):\n",
" \n",
" # Local variable b\n",
" b = 1\n",
" c = a * a + b\n",
" print(a, \"if you square + 1\", c) \n",
" return(c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The labels are displayed in the figure: \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/images/FuncsVar.png\" width=\"500\" />\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can call the function with an input of <b>3</b>:\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3 if you square + 1 10\n"
]
},
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Initializes Global variable \n",
"\n",
"x = 3\n",
"# Makes function call and return function a y\n",
"y = square(x)\n",
"y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" We can call the function with an input of <b>2</b> in a different manner:\n"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 if you square + 1 5\n"
]
},
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Directly enter a number as parameter\n",
"\n",
"square(2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If there is no <code>return</code> statement, the function returns <code>None</code>. The following two functions are equivalent:\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"# Define functions, one with return value None and other without return value\n",
"\n",
"def MJ():\n",
" print('Michael Jackson')\n",
" \n",
"def MJ1():\n",
" print('Michael Jackson')\n",
" return(None)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n"
]
}
],
"source": [
"# See the output\n",
"\n",
"MJ()"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n"
]
}
],
"source": [
"# See the output\n",
"\n",
"MJ1()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Printing the function after a call reveals a **None** is the default return statement:\n"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n",
"None\n",
"Michael Jackson\n",
"None\n"
]
}
],
"source": [
"# See what functions returns are\n",
"\n",
"print(MJ())\n",
"print(MJ1())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a function <code>con</code> that concatenates two strings using the addition operation:\n"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"# Define the function for combining strings\n",
"\n",
"def con(a, b):\n",
" return(a + b)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'This is'"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Test on the con() function\n",
"\n",
"con(\"This \", \"is\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr/>\n",
" <div class=\"alert alert-success alertsuccess\" style=\"margin-top: 20px\">\n",
" <h4> [Tip] How do I learn more about the pre-defined functions in Python? </h4>\n",
" <p>We will be introducing a variety of pre-defined functions to you as you learn more about Python. There are just too many functions, so there's no way we can teach them all in one sitting. But if you'd like to take a quick peek, here's a short reference card for some of the commonly-used pre-defined functions: <a href=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/Python_reference_sheet.pdf\">Reference</a></p>\n",
" </div>\n",
"<hr/>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3 id=\"simple\">Functions Make Things Simple</h3>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Consider the two lines of code in <b>Block 1</b> and <b>Block 2</b>: the procedure for each block is identical. The only thing that is different is the variable names and values.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h4>Block 1:</h4>\n"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# a and b calculation block1\n",
"\n",
"a1 = 4\n",
"b1 = 5\n",
"c1 = a1 + b1 + 2 * a1 * b1 - 1\n",
"if(c1 < 0):\n",
" c1 = 0 \n",
"else:\n",
" c1 = 5\n",
"c1 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h4>Block 2:</h4>\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# a and b calculation block2\n",
"\n",
"a2 = 0\n",
"b2 = 0\n",
"c2 = a2 + b2 + 2 * a2 * b2 - 1\n",
"if(c2 < 0):\n",
" c2 = 0 \n",
"else:\n",
" c2 = 5\n",
"c2 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can replace the lines of code with a function. A function combines many instructions into a single line of code. Once a function is defined, it can be used repeatedly. You can invoke the same function many times in your program. You can save your function and use it in another program or use someone else’s function. The lines of code in code <b>Block 1</b> and code <b>Block 2</b> can be replaced by the following function: \n"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"# Make a Function for the calculation above\n",
"\n",
"def Equation(a,b):\n",
" c = a + b + 2 * a * b - 1\n",
" if(c < 0):\n",
" c = 0 \n",
" else:\n",
" c = 5\n",
" return(c) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This function takes two inputs, a and b, then applies several operations to return c. \n",
"We simply define the function, replace the instructions with the function, and input the new values of <code>a1</code>, <code>b1</code> and <code>a2</code>, <code>b2</code> as inputs. The entire process is demonstrated in the figure: \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%203/images/FuncsPros.gif\" width=\"850\" />\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code **Blocks 1** and **Block 2** can now be replaced with code **Block 3** and code **Block 4**.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h4>Block 3:</h4>\n"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a1 = 4\n",
"b1 = 5\n",
"c1 = Equation(a1, b1)\n",
"c1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h4>Block 4:</h4>\n"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a2 = 0\n",
"b2 = 0\n",
"c2 = Equation(a2, b2)\n",
"c2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"pre\">Pre-defined functions</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are many pre-defined functions in Python, so let's start with the simple ones.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The <code>print()</code> function:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Build-in function print()\n",
"\n",
"album_ratings = [10.0, 8.5, 9.5, 7.0, 7.0, 9.5, 9.0, 9.5] \n",
"print(album_ratings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The <code>sum()</code> function adds all the elements in a list or tuple:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Use sum() to add every element in a list or tuple together\n",
"\n",
"sum(album_ratings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The <code>len()</code> function returns the length of a list or tuple: \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Show the length of the list or tuple\n",
"\n",
"len(album_ratings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"if\">Using <code>if</code>/<code>else</code> Statements and Loops in Functions</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The <code>return()</code> function is particularly useful if you have any IF statements in the function, when you want your output to be dependent on some condition: \n"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson Thriller 1980\n",
"Oldie\n"
]
}
],
"source": [
"# Function example\n",
"\n",
"def type_of_album(artist, album, year_released):\n",
" \n",
" print(artist, album, year_released)\n",
" if year_released > 1980:\n",
" return \"Modern\"\n",
" else:\n",
" return \"Oldie\"\n",
" \n",
"x = type_of_album(\"Michael Jackson\", \"Thriller\", 1980)\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use a loop in a function. For example, we can <code>print</code> out each element in a list:\n"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"# Print the list using for loop\n",
"\n",
"def PrintList(the_list):\n",
" for element in the_list:\n",
" print(element)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"1\n",
"the man\n",
"abc\n"
]
}
],
"source": [
"# Implement the printlist function\n",
"\n",
"PrintList(['1', 1, 'the man', \"abc\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"default\">Setting default argument values in your custom functions</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can set a default value for arguments in your function. For example, in the <code>isGoodRating()</code> function, what if we wanted to create a threshold for what we consider to be a good rating? Perhaps by default, we should have a default rating of 4:\n"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"# Example for setting param with default value\n",
"\n",
"def isGoodRating(rating=4): \n",
" if(rating < 7):\n",
" print(\"this album sucks it's rating is\",rating)\n",
" \n",
" else:\n",
" print(\"this album is good its rating is\",rating)\n"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"this album sucks it's rating is 5\n",
"this album is good its rating is 10\n"
]
}
],
"source": [
"# Test the value with default value and with input\n",
"\n",
"isGoodRating(5)\n",
"isGoodRating(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"global\">Global variables</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So far, we've been creating variables within functions, but we have not discussed variables outside the function. These are called global variables. \n",
"<br>\n",
"Let's try to see what <code>printer1</code> returns:\n"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson is an artist\n"
]
}
],
"source": [
"# Example of global variable\n",
"\n",
"artist = \"Michael Jackson\"\n",
"def printer1(artist):\n",
" internal_var1 = artist\n",
" print(artist, \"is an artist\")\n",
" \n",
"printer1(artist)\n",
"# try runningthe following code\n",
"#printer1(internal_var1) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>We got a Name Error: <code>name 'internal_var' is not defined</code>. Why?</b> \n",
"\n",
"It's because all the variables we create in the function is a <b>local variable</b>, meaning that the variable assignment does not persist outside the function. \n",
"\n",
"But there is a way to create <b>global variables</b> from within a function as follows:\n"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson is an artist\n",
"Whitney Houston is an artist\n"
]
}
],
"source": [
"artist = \"Michael Jackson\"\n",
"\n",
"def printer(artist):\n",
" global internal_var \n",
" internal_var= \"Whitney Houston\"\n",
" print(artist,\"is an artist\")\n",
"\n",
"printer(artist) \n",
"printer(internal_var)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"scope\">Scope of a Variable</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" The scope of a variable is the part of that program where that variable is accessible. Variables that are declared outside of all function definitions, such as the <code>myFavouriteBand</code> variable in the code shown here, are accessible from anywhere within the program. As a result, such variables are said to have global scope, and are known as global variables. \n",
" <code>myFavouriteBand</code> is a global variable, so it is accessible from within the <code>getBandRating</code> function, and we can use it to determine a band's rating. We can also use it outside of the function, such as when we pass it to the print function to display it:\n"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"AC/DC's rating is: 10.0\n",
"Deep Purple's rating is: 0.0\n",
"My favourite band is: AC/DC\n"
]
}
],
"source": [
"# Example of global variable\n",
"\n",
"myFavouriteBand = \"AC/DC\"\n",
"\n",
"def getBandRating(bandname):\n",
" if bandname == myFavouriteBand:\n",
" return 10.0\n",
" else:\n",
" return 0.0\n",
"\n",
"print(\"AC/DC's rating is:\", getBandRating(\"AC/DC\"))\n",
"print(\"Deep Purple's rating is:\",getBandRating(\"Deep Purple\"))\n",
"print(\"My favourite band is:\", myFavouriteBand)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Take a look at this modified version of our code. Now the <code>myFavouriteBand</code> variable is defined within the <code>getBandRating</code> function. A variable that is defined within a function is said to be a local variable of that function. That means that it is only accessible from within the function in which it is defined. Our <code>getBandRating</code> function will still work, because <code>myFavouriteBand</code> is still defined within the function. However, we can no longer print <code>myFavouriteBand</code> outside our function, because it is a local variable of our <code>getBandRating</code> function; it is only defined within the <code>getBandRating</code> function:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example of local variable\n",
"\n",
"def getBandRating(bandname):\n",
" myFavouriteBand = \"AC/DC\"\n",
" if bandname == myFavouriteBand:\n",
" return 10.0\n",
" else:\n",
" return 0.0\n",
"\n",
"print(\"AC/DC's rating is: \", getBandRating(\"AC/DC\"))\n",
"print(\"Deep Purple's rating is: \", getBandRating(\"Deep Purple\"))\n",
"print(\"My favourite band is\", myFavouriteBand)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Finally, take a look at this example. We now have two <code>myFavouriteBand</code> variable definitions. The first one of these has a global scope, and the second of them is a local variable within the <code>getBandRating</code> function. Within the <code>getBandRating</code> function, the local variable takes precedence. **Deep Purple** will receive a rating of 10.0 when passed to the <code>getBandRating</code> function. However, outside of the <code>getBandRating</code> function, the <code>getBandRating</code> s local variable is not defined, so the <code>myFavouriteBand</code> variable we print is the global variable, which has a value of **AC/DC**:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example of global variable and local variable with the same name\n",
"\n",
"myFavouriteBand = \"AC/DC\"\n",
"\n",
"def getBandRating(bandname):\n",
" myFavouriteBand = \"Deep Purple\"\n",
" if bandname == myFavouriteBand:\n",
" return 10.0\n",
" else:\n",
" return 0.0\n",
"\n",
"print(\"AC/DC's rating is:\",getBandRating(\"AC/DC\"))\n",
"print(\"Deep Purple's rating is: \",getBandRating(\"Deep Purple\"))\n",
"print(\"My favourite band is:\",myFavouriteBand)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"<h2 id =\"collec\"> Collections and Functions</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When the number of arguments are unknown for a function, They can all be packed into a tuple as shown:\n"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"No of arguments: 3\n",
"Horsefeather\n",
"Adonis\n",
"Bone\n",
"No of arguments: 4\n",
"Sidecar\n",
"Long Island\n",
"Mudslide\n",
"Carriage\n"
]
}
],
"source": [
"def printAll(*args): # All the arguments are 'packed' into args which can be treated like a tuple\n",
" print(\"No of arguments:\", len(args)) \n",
" for argument in args:\n",
" print(argument)\n",
"#printAll with 3 arguments\n",
"printAll('Horsefeather','Adonis','Bone')\n",
"#printAll with 4 arguments\n",
"printAll('Sidecar','Long Island','Mudslide','Carriage')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similarly, The arguments can also be packed into a dictionary as shown: \n"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Country : Canada\n",
"Province : Ontario\n",
"City : Toronto\n"
]
}
],
"source": [
"def printDictionary(**args):\n",
" for key in args:\n",
" print(key + \" : \" + args[key])\n",
"\n",
"printDictionary(Country='Canada',Province='Ontario',City='Toronto')\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Functions can be incredibly powerful and versatile. They can accept (and return) data types, objects and even other functions as arguements. Consider the example below: \n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['One', 'Two', 'Three', 'Four']"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def addItems(list):\n",
" list.append(\"Three\")\n",
" list.append(\"Four\")\n",
"\n",
"myList = [\"One\",\"Two\"]\n",
"\n",
"addItems(myList)\n",
"\n",
"myList\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note how the changes made to the list are not limited to the functions scope. This occurs as it is the lists **reference** that is passed to the function - Any changes made are on the orignal instance of the list. Therefore, one should be cautious when passing mutable objects into functions.\n",
"\n",
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2>Quiz on Functions</h2>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Come up with a function that divides the first input by the second input:\n"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2.0"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"def divide(input1, input2):\n",
" result=input1/input2\n",
" return(result)\n",
"divide(6,3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"def div(a, b):\n",
" return(a/b)\n",
" \n",
"```\n",
"\n",
"</details>\n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use the function <code>con</code> for the following question.\n"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the con function for the following question\n",
"\n",
"def con(a, b):\n",
" return(a + b)\n",
"con(5,6)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can the <code>con</code> function we defined before be used to add two integers or strings?\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'My name is Michael Jordan'"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"con('My name is', ' Michael Jordan')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"Yes, for example: \n",
"con(2, 2)\n",
" \n",
"```\n",
"\n",
"</details>\n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can the <code>con</code> function we defined before be used to concatenate lists or tuples?\n"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4, 5, 6]"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"con([1,2,3],[4,5,6])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"Yes, for example: \n",
"con(['a', 1], ['b', 1])\n",
" \n",
"```\n",
"\n",
"</details>\n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Probability Bag**\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You have been tasked with creating a lab that demonstrates the basics of probability by simulating a bag filled with colored balls. The bag is represented using a dictionary called \"bag\", where the key represents the color of the ball and the value represents the no of balls. The skeleton code has been made for you, do not add or remove any functions. Complete the following functions -\n",
"\n",
"- fillBag - A function that packs it's arguments into a global dictionary \"bag\". \n",
"- totalBalls - returns the total no of balls in the bucket\n",
"- probOf - takes a color (string) as argument and returns probability of drawing the selected ball. Assume total balls are not zero and the color given is a valid key.\n",
"- probAll - returns a dictionary of all colors and their corresponding probability\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def fillBag(**balls):\n",
" global bag\n",
" bag = balls\n",
"\n",
"def totalBalls():\n",
" total = 0\n",
" for color in bag:\n",
" total += bag[color]\n",
" return total\n",
" # alternatively,\n",
" # return sum(bag.values())\n",
"\n",
"def probOf(color):\n",
" return bag[color]/totalBalls()\n",
"\n",
"def probAll():\n",
" probDict = {}\n",
" for color in bag:\n",
" probDict[color] = probOf(color)\n",
" return probDict\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Run this snippet of code to test your solution. \n",
"\n",
"Note: This is not a comprehensive test. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"hide"
]
},
"outputs": [],
"source": [
"\n",
"testBag = dict(red = 12, blue = 20, green = 14, grey = 10)\n",
"total = sum(testBag.values())\n",
"prob={}\n",
"for color in testBag:\n",
" prob[color] = testBag[color]/total;\n",
"\n",
"def testMsg(passed):\n",
" if passed:\n",
" return 'Test Passed'\n",
" else :\n",
" return ' Test Failed'\n",
"\n",
"print(\"fillBag : \")\n",
"try:\n",
" fillBag(**testBag)\n",
" print(testMsg(bag == testBag))\n",
"except NameError as e: \n",
" print('Error! Code: {c}, Message: {m}'.format(c = type(e).__name__, m = str(e)))\n",
"except:\n",
" print(\"An error occured. Recheck your function\")\n",
"\n",
"\n",
"\n",
"print(\"totalBalls : \")\n",
"try:\n",
" print(testMsg(total == totalBalls()))\n",
"except NameError as e: \n",
" print('Error! Code: {c}, Message: {m}'.format(c = type(e).__name__, m = str(e)))\n",
"except:\n",
" print(\"An error occured. Recheck your function\")\n",
" \n",
"print(\"probOf\")\n",
"try:\n",
" passed = True\n",
" for color in testBag:\n",
" if probOf(color) != prob[color]:\n",
" passed = False\n",
" \n",
" print(testMsg(passed) )\n",
"except NameError as e: \n",
" print('Error! Code: {c}, Message: {m}'.format(c = type(e).__name__, m = str(e)))\n",
"except:\n",
" print(\"An error occured. Recheck your function\")\n",
" \n",
"print(\"probAll\")\n",
"try:\n",
" print(testMsg(probAll() == prob))\n",
"except NameError as e: \n",
" print('Error! Code: {c}, Message: {m}'.format(c = type(e).__name__, m = str(e)))\n",
"except:\n",
" print(\"An error occured. Recheck your function\")\n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<details><summary>Click here for the solution</summary>\n",
"\n",
"```python\n",
"def fillBag(**balls):\n",
" global bag\n",
" bag = balls\n",
" \n",
"def totalBalls():\n",
" total = 0\n",
" for color in bag:\n",
" total += bag[color]\n",
" return total\n",
" # alternatively,\n",
" # return sum(bag.values())\n",
" \n",
"def probOf(color):\n",
" return bag[color]/totalBalls()\n",
"\n",
"def probAll():\n",
" probDict = {}\n",
" for color in bag:\n",
" probDict[color] = probOf(color)\n",
" return probDict\n",
" \n",
"```\n",
"\n",
"</details>\n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"<h2>The last exercise!</h2>\n",
"<p>Congratulations, you have completed your first lesson and hands-on lab in Python. However, there is one more thing you need to do. The Data Science community encourages sharing work. The best way to share and showcase your work is to share it on GitHub. By sharing your notebook on GitHub you are not only building your reputation with fellow data scientists, but you can also show it off when applying for a job. Even though this was your first piece of work, it is never too early to start building good habits. So, please read and follow <a href=\"https://cognitiveclass.ai/blog/data-scientists-stand-out-by-sharing-your-notebooks/\" target=\"_blank\">this article</a> to learn how to share your work.\n",
"<hr>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Author\n",
"\n",
"<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n",
"\n",
"## Other contributors\n",
"\n",
"<a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a>\n",
"\n",
"## Change Log\n",
"\n",
"| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n",
"| ----------------- | ------- | ---------- | ---------------------------------------------------------------------------------------------------------------------- |\n",
"| 2020-08-26 | 0.2 | Lavanya | Moved lab to course repo in GitLab |\n",
"| 2020 -09 -04 | 0.2 | Arjun | Under What is a function, added code/text to further demonstrate the functionality of the return statement |\n",
"| 2020 -09 -04 | 0.2 | Arjun | Under Global Variables, modify the code block to try and print ‘internal_var’ - So a nameError message can be observed |\n",
"| 2020 -09 -04 | 0.2 | Arjun | Added section Collections and Functions |\n",
"| 2020 -09 -04 | 0.2 | Arjun | Added exercise “Probability Bag” |\n",
"\n",
"<hr/>\n",
"\n",
"## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python",
"language": "python",
"name": "conda-env-python-py"
},
"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.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment