Skip to content

Instantly share code, notes, and snippets.

@salamituns
Created February 14, 2021 16:06
Show Gist options
  • Save salamituns/0a2af730f6571c6057a4ce193be0efd5 to your computer and use it in GitHub Desktop.
Save salamituns/0a2af730f6571c6057a4ce193be0efd5 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": [
" Functions in Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A function is a reusable block of code which performs operations specified in the function."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here are simple rules to define a function in Python:\n",
" 1. 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",
" 2. 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",
" 3. The statement 'return' exits a function, optionally passing back a value."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"#Example of a function:\n",
"#This function will Add 1 to 'a' and store as 'b'\n",
"\n",
"def add(a):\n",
" b = a + 1\n",
" print(a, 'if you add 1', b)\n",
" return(b)"
]
},
{
"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",
"help(add)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can create different functions. For example, we can create a function that multiplies two numbers. \n",
"The numbers will be represented by the variables a and b:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"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 written above can be used for different data types. \n",
"For example, we can multiply two integers:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"31.400000000000002"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mult(10.0, 3.14)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Michael Jackson Michael Jackson '"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#We can even replicate a string by multiplying with an integer:\n",
"mult(2, \"Michael Jackson \")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Variables.\n",
"A variable that is declared inside a function is called a 'local variable'(parameter only exists within the function)\n",
"A variable that is declared outside a function definition is a 'global variable'\n",
" i.e: its value is accessible and modifiable throughout the program."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 if you square + 1 5\n"
]
},
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"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)\n",
"\n",
"x = 2\n",
"# Makes function call and return function a y\n",
"y = square(x)\n",
"y"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 if you square + 1 5\n"
]
},
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#We can also call the function with an input of 2 in a different manner:\n",
"square(2)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n"
]
}
],
"source": [
"# Define functions, one with return value None and other without return value\n",
"\n",
"def MJ():\n",
" print('Michael Jackson')\n",
"MJ()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson\n"
]
}
],
"source": [
"def MJ1():\n",
" print('Michael Jackson')\n",
" return(None)\n",
"MJ1()"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'This is'"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Define the function for combining strings\n",
"\n",
"def con(a, b):\n",
" return(a + b)\n",
"\n",
"con(\"This \", \"is\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A function combines many instructions into a single line of code."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#Block 1\n",
"# 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": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#Block 2\n",
"# 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 above lines of code with a function."
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"# Making a Function for the calculation in the blocks 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) \n",
"\n",
"#we will replace the code in block 1 & 2 with codes in block 3 & 4"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#block 3\n",
"\n",
"a1 = 4\n",
"b1 = 5\n",
"c1 = Equation(a1, b1)\n",
"c1"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#block 4\n",
"\n",
"a2 = 0\n",
"b2 = 0\n",
"c2 = Equation(a2, b2)\n",
"c2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using the built-in functions in python"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"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": "code",
"execution_count": 63,
"metadata": {},
"outputs": [],
"source": [
"album_ratings.sort()"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"70.0"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#The sum() function adds all the elements in a list or tuple:\n",
"\n",
"sum(album_ratings) "
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#The len() function returns the length of a list or tuple:\n",
"\n",
"len(album_ratings) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Using if/else Statements and Loops in Functions"
]
},
{
"cell_type": "code",
"execution_count": 33,
"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": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"1\n",
"the man\n",
"abc\n"
]
}
],
"source": [
"# Print the list using 'for' loop\n",
"def PrintList(the_list):\n",
" for element in the_list:\n",
" print(element)\n",
"\n",
"# Implement the printlist function \n",
"PrintList(['1', 1, 'the man', \"abc\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Setting default argument values in a custom functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For example, in the isGoodRating() function below, We want to create a threshold for what we consider to be a good rating.\n",
"By default, we whould have a default rating of 4:"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This album sucks, its rating is 4\n",
"This album is good, its rating is 10\n"
]
}
],
"source": [
"def isGoodRating(rating = 4):\n",
" if (rating < 7):\n",
" print('This album sucks, its rating is', rating)\n",
" \n",
" else:\n",
" print('This album is good, its rating is', rating)\n",
"\n",
"#Then we test the value with default value and with input\n",
"isGoodRating()\n",
"isGoodRating(10)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson is an artist\n"
]
},
{
"ename": "NameError",
"evalue": "name 'internal_var1' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-39-86438c577ebc>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mprinter1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0martist\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;31m# try runningthe following code\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mprinter1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minternal_var1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'internal_var1' is not defined"
]
}
],
"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": [
"We got an error because the 'interval_var1' is a local variable.\n",
" A variable that is defined within a function is said to be a local variable of that function. \n",
"Meaning that the variable assignment does not persist outside the function."
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Michael Jackson is an artist\n",
"Whitney Houston is an artist\n"
]
}
],
"source": [
"#Here's how a created a global variable out of this function\n",
"\n",
"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": "code",
"execution_count": 41,
"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\" #Already declared here as a global brand outside of the function.\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": "code",
"execution_count": 42,
"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 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": "code",
"execution_count": 43,
"metadata": {},
"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": [
" Collections and Functions"
]
},
{
"cell_type": "code",
"execution_count": 44,
"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": "code",
"execution_count": 45,
"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')"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['One', 'Two', 'Three', 'Four']"
]
},
"execution_count": 46,
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Quiz on Functions"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4.0\n"
]
}
],
"source": [
"#Come up with a function that divides the first input by the second input:\n",
"\n",
"def div(a, b):\n",
" c = a / b\n",
" return(c)\n",
"\n",
"answer= div(20, 5)\n",
"print(answer)"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"30\n"
]
}
],
"source": [
"# Use the con function for the following question to add two integers or strings\n",
"\n",
"def con(a, b):\n",
" return(a + b)\n",
"\n",
"result=con(20, 10)\n",
"print(result)"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[3, 1, 1, 2]"
]
},
"execution_count": 53,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"con([3, 1], [1, 2])"
]
},
{
"cell_type": "code",
"execution_count": 59,
"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"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 64,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def add(x):\n",
" return(x+x)\n",
" \n",
"add(1)"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [],
"source": [
"def hello():\n",
" print(\"hello\")"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-67-07ac9dfe2c9e>, line 1)",
"output_type": "error",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"<ipython-input-67-07ac9dfe2c9e>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m def add(1, 2):\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"def add(1, 2):\n",
" output = 1 + 2\n",
" return(output)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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