Skip to content

Instantly share code, notes, and snippets.

@letscode0410
Created December 13, 2018 06:40
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 letscode0410/307b6a709ca9d149db93ab216480206f to your computer and use it in GitHub Desktop.
Save letscode0410/307b6a709ca9d149db93ab216480206f 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": "markdown",
"metadata": {},
"source": [
" <div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
" <a href=\"http://cocl.us/NotebooksPython101\"><img src = \"https://ibm.box.com/shared/static/yfe6h4az47ktg2mm9h05wby2n7e8kei3.png\" width = 750, align = \"center\"></a>\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a href=\"https://www.bigdatauniversity.com\"><img src = \"https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4kqnvvk3bq1g.png\" width = 300, align = \"center\"></a>\n",
"\n",
"<h1 align=center><font size = 5>WRITING YOUR OWN FUNCTIONS IN PYTHON</font></h1>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Table of Contents\n",
"\n",
"\n",
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n",
"<ol>\n",
"\n",
"<li><a href=\"#ref1\">What is a Function?</a></li>\n",
"<li><a href=\"#ref3\">Using if/else statements in functions</a></li>\n",
"<li><a href=\"#ref4\">Setting default argument values in your custom functions</a></li>\n",
"<li><a href=\"#ref6\">Global and local variables</a></li>\n",
"<li><a href=\"#ref7\">Scope of a Variable </a></li>\n",
"\n",
"</ol>\n",
"<br>\n",
"<p></p>\n",
"Estimated Time Needed: <strong>40 min</strong>\n",
"</div>\n",
"\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='ref1'></a>\n",
"<center><h2>Defining a Function</h2></center>\n",
"\n",
"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",
"\n",
"- **Pre-defined functions**\n",
"- **User defined functions**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3>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 **def** followed by the function **name** and parentheses **()**.\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 (**:**) and is indented.\n",
"- You can also place documentation before the body \n",
"- The statement **return** exits a function, optionally passing back a value \n",
"\n",
"An example of a function that adds on to the parameter **a** prints and returns the output as **b**:\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def add(a):\n",
" \"\"\"\n",
" add 1 to a\n",
" \"\"\"\n",
" b=a+1; \n",
" print(a, \"if you add one\" ,b)\n",
" \n",
" return(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The figure below illustrates the terminology: "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a ><img src = \"https://ibm.box.com/shared/static/wsl6jcfld2c3171ob19vjr5chw9gyxrc.png\" width = 500, align = \"center\"></a>\n",
" <h4 align=center> \n",
" A labeled function\n",
" </h4> "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" We can obtain help about a function :"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on function add in module __main__:\n",
"\n",
"add(a)\n",
" add 1 to a\n",
"\n"
]
}
],
"source": [
"help(add)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can call the function:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 if you add one 2\n"
]
},
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"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": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 if you add one 3\n"
]
},
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"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 **a** and **b**:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def Mult(a,b):\n",
" \"\"\"\n",
" multiples a with b\n",
" \"\"\"\n",
" c=a*b\n",
" return(c)"
]
},
{
"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": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on function Mult in module __main__:\n",
"\n",
"Mult(a, b)\n",
" multiples a with b\n",
"\n"
]
}
],
"source": [
"Mult(2,3)\n",
"help(Mult)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Two Floats: "
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"31.400000000000002"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Mult(10,3.14)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can even replicate a string by multiplying with an integer: "
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'Michael Jackson Michael Jackson '"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Mult(2,\"Michael Jackson \")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Come up with a function that divides the first input by the second input:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def Devide(a,b):\n",
" \"\"\"\n",
" a will be devided by b\n",
" \"\"\"\n",
" c=a/b\n",
" return c"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"<!-- \n",
"def div(a,b):\n",
" return(a/b)\n",
" -->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <h3>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": 13,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#Function Definition \n",
"def square(a):\n",
" \"\"\"Square the input and add one \n",
" \"\"\"\n",
" #Local variable \n",
" b=1\n",
" c=a*a+b;\n",
" print(a, \"if you square +1 \",c) \n",
" return(c)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The labels are displayed in the figure: "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a ><img src = \"https://ibm.box.com/shared/static/gpfa525nnfwxt5rhrvd3o6i8rp2iwsai.png\" width = 500, align = \"center\"></a>\n",
" <h4 align=center> \n",
" Figure 2: A function with labeled variables \n",
" </h4> \n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can call the function with an input of 3:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3 if you square +1 10\n"
]
},
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#Initializes Global variable \n",
"\n",
"x=3\n",
"#Makes function call and return function a y\n",
"z=square(x)\n",
"z"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" We can call the function with an input of 2 in a different manner:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 if you square +1 5\n"
]
},
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"square(2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" If there is no **return** statement, the function returns **None**. The following two functions are equivalent: \n",
" "
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def MJ():\n",
" print('Michael Jackson')\n",
" \n",
"def MJ1():\n",
" print('Michael Jackson')\n",
" return(None)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n"
]
}
],
"source": [
"MJ()"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n"
]
}
],
"source": [
"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": 19,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n",
"None\n",
"Michael Jackson\n",
"None\n"
]
}
],
"source": [
"print(MJ())\n",
"print(MJ1())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a function **con** that concatenates two strings using the addition operation:\n",
": "
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def con(a,b):\n",
" return(a+b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"<!-- \n",
"def div(a,b):\n",
" return(a+b)\n",
" -->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Can the same function be used to add to integers or strings?"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"con(4,4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Double-click __here__ for the solution.\n",
"<!-- \n",
"yes,for example: \n",
"con(2,2)\n",
" -->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Can the same function be used to concentrate a list or tuple?"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"(2, 3, 4, 5, 6, 7)"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"con((2,3,4),(5,6,7))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double-click __here__ for the solution.\n",
"<!-- \n",
"yes,for example: \n",
"con(['a',1],['b',1])\n",
" -->"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3><b>Pre-defined functions</b></h3>"
]
},
{
"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 **print()** function:"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[10.0, 8.5, 9.5, 7.0, 7.0, 9.5, 9.0, 9.5]\n"
]
}
],
"source": [
"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 **sum()** function adds all the elements in a list or tuple:"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"70.0"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum(album_ratings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" The length function returns the length of a list or tuple: "
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(album_ratings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<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></p>\n",
"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: \n",
"http://www.astro.up.pt/~sousasag/Python_For_Astronomers/Python_qr.pdf\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h3>Functions Makes Things Simple </h3>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Consider the two lines of code in **Block 1** and **Block 2**: 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": [
"### Block 1:"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"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": [
"### Block 2:"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"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 **block 1** and code **block 2** can be replaced by the following function: \n",
" \n"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def Equation(a,b):\n",
" c=a+b+2*a*b-1\n",
" if(c<0):\n",
" c=0\n",
" \n",
" else:\n",
" c=5\n",
" return(c) \n"
]
},
{
"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 **a1**,**b1** and **a2**,**b2** as inputs. The entire process is demonstrated in the figure: "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a ><img src = \"https://ibm.box.com/shared/static/efn4rii75bgytjdb5c8ek6uezch7yaxq.gif\" width = 1100, align = \"center\"></a>\n",
" <h4 align=center> \n",
" Example of a function used to replace redundant lines of code \n",
" </h4> "
]
},
{
"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": [
"### Block 3:"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a1=4;\n",
"b1=5;\n",
"c1=Equation(a1,b1)\n",
"c1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Block 4:"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a2=0;\n",
"b2=0;\n",
"c2=Equation(a2,b2)\n",
"c2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='ref3'></a>\n",
"<center><h2>Using if/else statements and loops in functions</h2></center>\n",
"\n",
"The **return()** 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": 31,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson Thriller 1980\n",
"Oldie\n"
]
}
],
"source": [
"def type_of_album(artist,album,year_released):\n",
" if year_released > 1980:\n",
" print(artist,album,year_released)\n",
" return \"Modern\"\n",
" else:\n",
" print(artist,album,year_released)\n",
" return \"Oldie\"\n",
" \n",
"x = type_of_album(\"Michael Jackson\",\"Thriller\",1980)\n",
"print(x)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" We can use a loop in a function. For example, we can **print** out each element in a list:"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def PrintList(the_list):\n",
" for element in the_list:\n",
" print(element)"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"1\n",
"the man\n",
"abc\n"
]
}
],
"source": [
"PrintList(['1',1,'the man',\"abc\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='ref4'></a>\n",
"<center><h2>Setting default argument values in your custom functions</h2></center>\n",
"\n",
"You can set a default value for arguments in your function. For example, in the **`isGoodRating()`** 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": 34,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"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": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"this album sucks it's rating is 4\n",
"this album is good its rating is 10\n"
]
}
],
"source": [
"isGoodRating()\n",
"isGoodRating(10)\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='ref6'></a>\n",
"<center><h2>Global variables</h2></center>\n",
"<br>\n",
"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 **printer1** returns:"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson is an artist\n"
]
}
],
"source": [
"artist = \"Michael Jackson\"\n",
"def printer1(artist):\n",
" internal_var = artist\n",
" print(artist,\"is an artist\")\n",
" \n",
"printer1(artist)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" If we print **internal_var** we get an error. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**We got a Name Error:** `name 'internal_var' is not defined`. **Why?** \n",
"\n",
"It's because all the variables we create in the function is a **local variable**, meaning that the variable assignment does not persist outside the function. \n",
"\n",
"But there is a way to create **global variables** from within a function as follows:"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": false
},
"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)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <a id='ref7'></a>\n",
"<center><h2>Scope of a Variable</h2></center>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>"
]
},
{
"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 **myFavouriteBand** 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",
" **myFavouriteBand** is a global variable, so it is accessible from within the **getBandRating** 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": 38,
"metadata": {
"collapsed": 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": [
"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 **myFavouriteBand** variable is defined within the **getBandRating** 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 **getBandRating** function will still work, because **myFavouriteBand** is still defined within the function. However, we can no longer print **myFavouriteBand** outside our function, because it is a local variable of our **getBandRating** function; it is only defined within the **getBandRating** function:"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": 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": [
"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 **myFavouriteBand** variable definitions. The first one of these has a global scope, and the second of them is a local variable within the **getBandRating** function. Within the **getBandRating** function, the local variable takes precedence. **Deep Purple** will receive a rating of 10.0 when passed to the **getBandRating** function. However, outside of the **getBandRating** function, the **getBandRating** s local variable is not defined, so the **myFavouriteBand** variable we print is the global variable, which has a value of **AC/DC**:"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": 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": [
"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": [
" <a href=\"http://cocl.us/NotebooksPython101bottom\"><img src = \"https://ibm.box.com/shared/static/irypdxea2q4th88zu1o1tsd06dya10go.png\" width = 750, align = \"center\"></a>\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"# About the Authors: \n",
"\n",
" [Joseph Santarcangelo]( https://www.linkedin.com/in/joseph-s-50398b136/) has 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.\n",
" \n",
" [James Reeve]( https://www.linkedin.com/in/reevejamesd/) James Reeves is a Software Engineering intern at IBM."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <hr>\n",
"Copyright &copy; 2017 [cognitiveclass.ai](cognitiveclass.ai?utm_source=bducopyrightlink&utm_medium=dswb&utm_campaign=bdu). This notebook and its source code are released under the terms of the [MIT License](https://bigdatauniversity.com/mit-license/)."
]
}
],
"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.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment