Skip to content

Instantly share code, notes, and snippets.

@danielle-b
Created July 27, 2019 02:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save danielle-b/ff1e32935494cb2a0b32cbb2d12e5a5b to your computer and use it in GitHub Desktop.
Created on Cognitive Class Labs
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "raw",
"metadata": {},
"source": [
"<a href=\"https://cognitiveclass.ai/\">\n",
" <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/CCLog.png\" width=\"200\" align=\"center\">\n",
"</a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h1>Functions in Python</h1>"
]
},
{
"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>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
" <a href=\"https://cocl.us/topNotebooksPython101Coursera\">\n",
" <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/TopAd.png\" width=\"750\" align=\"center\">\n",
" </a>\n",
"</div>"
]
},
{
"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>\n",
" <a href=\"#quiz\">Quiz on Loops</a>\n",
" </li>\n",
" </ul>\n",
" <p>\n",
" Estimated time needed: <strong>40 min</strong>\n",
" </p>\n",
"</div>\n",
"\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"func\">Functions</h2>"
]
},
{
"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>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3 id=\"content\">What is a Function?</h3>"
]
},
{
"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",
"- 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>:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"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)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The figure below illustrates the terminology: "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%203/Images/FuncsDefinition.png\" width=\"500\" /> "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can obtain help about a function :"
]
},
{
"cell_type": "code",
"execution_count": 5,
"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",
"def add(a):\n",
" b = a + 1\n",
" print(a, \"if you add one\", b)\n",
" return(b)\n",
"\n",
"help(add)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can call the function:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 if you add one 2\n"
]
},
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Call the function add()\n",
"\n",
"def add(a):\n",
" b = a + 1\n",
" print(a, \"if you add one\", b)\n",
" return (b)\n",
"\n",
"add(1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we call the function with a new input we get a new result:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 if you add one 3\n"
]
},
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Call the function add()\n",
"\n",
"def add(a):\n",
" b = a + 1\n",
" print(a, \"if you add one\", b)\n",
" return (b)\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>:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"# Define a function for multiple two numbers\n",
"\n",
"def Mult(a, b):\n",
" c = a * b\n",
" return (c)\n"
]
},
{
"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": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6\n"
]
}
],
"source": [
"# Use mult() multiply two integers\n",
"\n",
"def Mult(a, b):\n",
" c = a * b\n",
" return (c)\n",
"\n",
"print(Mult(2, 3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Two Floats: "
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"31.400000000000002\n"
]
}
],
"source": [
"# Use mult() multiply two floats\n",
"\n",
"def Mult(a, b):\n",
" c = a * b\n",
" return (c)\n",
"\n",
"print (Mult(10.0, 3.14))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can even replicate a string by multiplying with an integer: "
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Michael Jackson Michael Jackson '"
]
},
"execution_count": 12,
"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>"
]
},
{
"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": 4,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"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: "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%203/Images/FuncsVar.png\" width=\"500\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can call the function with an input of <b>3</b>:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3 if you square + 1 10\n"
]
},
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 5,
"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:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 if you square + 1 5\n"
]
},
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 6,
"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:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"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": 8,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n"
]
}
],
"source": [
"# See the output\n",
"\n",
"MJ()"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"# Define the function for combining strings\n",
"\n",
"def con(a, b):\n",
" return(a + b)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'This is'"
]
},
"execution_count": 13,
"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=\"http://www.astro.up.pt/~sousasag/Python_For_Astronomers/Python_qr.pdf\">Reference</a></p>\n",
" </div>\n",
"<hr/>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3 id=\"simple\">Functions Make Things Simple</h3>"
]
},
{
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h4>Block 1:</h4>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"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>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"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: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"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: "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%203/Images/FuncsPros.gif\" width=\"850\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code **Blocks 1** and **Block 2** can now be replaced with code **Block 3** and code **Block 4**."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h4>Block 3:</h4>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"a1 = 4\n",
"b1 = 5\n",
"c1 = Equation(a1, b1)\n",
"c1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h4>Block 4:</h4>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"a2 = 0\n",
"b2 = 0\n",
"c2 = Equation(a2, b2)\n",
"c2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"pre\">Pre-defined functions</h2>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are many pre-defined functions in Python, so let's start with the simple ones."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The <code>print()</code> function:"
]
},
{
"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:"
]
},
{
"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: "
]
},
{
"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>"
]
},
{
"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: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"jupyter": {
"outputs_hidden": true
}
},
"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": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"# Implement the printlist function\n",
"\n",
"PrintList(['1', 1, 'the man', \"abc\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"default\">Setting default argument values in your custom functions</h2>"
]
},
{
"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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"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": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"# Test the value with default value and with input\n",
"\n",
"isGoodRating()\n",
"isGoodRating(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"global\">Global variables</h2>"
]
},
{
"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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"# Example of global variable\n",
"\n",
"artist = \"Michael Jackson\"\n",
"def printer1(artist):\n",
" internal_var = artist\n",
" print(artist, \"is an artist\")\n",
" \n",
"printer1(artist)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we print <code>internal_var</code> we get an error. "
]
},
{
"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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"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>"
]
},
{
"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:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"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 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**:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"AC/DC's rating is: 0.0\n",
"Deep Purple's rating is: 10.0\n",
"My favourite band is: AC/DC\n"
]
}
],
"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": [
"<h2>Quiz on Functions</h2>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Come up with a function that divides the first input by the second input:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"\n",
"def div (a, b):\n",
" return (a/b)"
]
},
{
"cell_type": "markdown",
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"source": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- \n",
"def div(a, b):\n",
" return(a/b)\n",
"-->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use the function <code>con</code> for the following question."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Use the con function for the following question\n",
"\n",
"def con(a, b):\n",
" return(a + b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can the <code>con</code> function we defined before be used to add to integers or strings?"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"\n",
"yes\n",
"\n",
"con(5, 4)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"source": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- \n",
"yes, for example: \n",
"con(2, 2)\n",
" -->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can the <code>con</code> function we defined before be used to concentrate a list or tuple?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Write your code below and press Shift+Enter to execute\n",
"\n",
"Yes,\n",
"con({'d', 4}, {'k', 11})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"\n",
"<!-- \n",
"yes,for example: \n",
"con(['a', 1], ['b', 1])\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>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
"<h2>Get IBM Watson Studio free of charge!</h2>\n",
" <p><a href=\"https://cocl.us/bottemNotebooksPython101Coursera\"><img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/BottomAd.png\" width=\"750\" align=\"center\"></a></p>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3>About the Authors:</h3> \n",
"<p><a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a> is a Data Scientist at IBM, and holds a PhD in Electrical Engineering. His research focused on using Machine Learning, Signal Processing, and Computer Vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.</p>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Other contributors: <a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a>, <a href=\"https://www.linkedin.com/in/reevejamesd/\">James Reeve</a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<p>Copyright &copy; 2018 IBM Developer Skills Network. This notebook and its source code are released under the terms of the <a href=\"https://cognitiveclass.ai/mit-license/\">MIT License</a>.</p>"
]
}
],
"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.7"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment