{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "All the IPython Notebooks in this lecture series are available at https://github.com/rajathkumarmp/Python-Lectures" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Most of the times, In a algorithm the statements keep repeating and it will be a tedious job to execute the same statements again and again and will consume a lot of memory and is not efficient. Enter Functions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is the basic syntax of a function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "def funcname(arg1, arg2,... argN):\n", " \n", " ''' Document String'''\n", "\n", " statements\n", "\n", "\n", " return " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Read the above syntax as, A function by name \"funcname\" is defined, which accepts arguements \"arg1,arg2,....argN\". The function is documented and it is '''Document String'''. The function after executing the statements returns a \"value\"." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hey Rajath!\n", "Rajath, How do you do?\n" ] } ], "source": [ "print \"Hey Rajath!\"\n", "print \"Rajath, How do you do?\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Instead of writing the above two statements every single time it can be replaced by defining a function which would do the job in just one line. \n", "\n", "Defining a function firstfunc()." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def firstfunc():\n", " print \"Hey Rajath!\"\n", " print \"Rajath, How do you do?\" " ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hey Rajath!\n", "Rajath, How do you do?\n" ] } ], "source": [ "firstfunc()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**firstfunc()** every time just prints the message to a single person. We can make our function **firstfunc()** to accept arguements which will store the name and then prints respective to that accepted name. To do so, add a argument within the function as shown." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def firstfunc(username):\n", " print \"Hey\", username + '!'\n", " print username + ',' ,\"How do you do?\"" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Please enter your name : Guido\n" ] } ], "source": [ "name1 = raw_input('Please enter your name : ')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The name \"Guido\" is actually stored in name1. So we pass this variable to the function **firstfunc()** as the variable username because that is the variable that is defined for this function. i.e name1 is passed as username." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hey Guido!\n", "Guido, How do you do?\n" ] } ], "source": [ "firstfunc(name1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us simplify this even further by defining another function **secondfunc()** which accepts the name and stores it inside a variable and then calls the **firstfunc()** from inside the function itself." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def firstfunc(username):\n", " print \"Hey\", username + '!'\n", " print username + ',' ,\"How do you do?\"\n", "def secondfunc():\n", " name = raw_input(\"Please enter your name : \")\n", " firstfunc(name)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Please enter your name : karthik\n", "Hey karthik!\n", "karthik, How do you do?\n" ] } ], "source": [ "secondfunc()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Return Statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When the function results in some value and that value has to be stored in a variable or needs to be sent back or returned for further operation to the main algorithm, return statement is used." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def times(x,y):\n", " z = x*y\n", " return z" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The above defined **times( )** function accepts two arguements and return the variable z which contains the result of the product of the two arguements" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20\n" ] } ], "source": [ "c = times(4,5)\n", "print c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The z value is stored in variable c and can be used for further operations." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Instead of declaring another variable the entire statement itself can be used in the return statement as shown." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def times(x,y):\n", " '''This multiplies the two input arguments'''\n", " return x*y" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20\n" ] } ], "source": [ "c = times(4,5)\n", "print c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since the **times( )** is now defined, we can document it as shown above. This document is returned whenever **times( )** function is called under **help( )** function." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function times in module __main__:\n", "\n", "times(x, y)\n", " This multiplies the two input arguments\n", "\n" ] } ], "source": [ "help(times)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Multiple variable can also be returned, But keep in mind the order." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": true }, "outputs": [], "source": [ "eglist = [10,50,30,12,6,8,100]" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def egfunc(eglist):\n", " highest = max(eglist)\n", " lowest = min(eglist)\n", " first = eglist[0]\n", " last = eglist[-1]\n", " return highest,lowest,first,last" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If the function is just called without any variable for it to be assigned to, the result is returned inside a tuple. But if the variables are mentioned then the result is assigned to the variable in a particular order which is declared in the return statement." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(100, 6, 10, 100)" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "egfunc(eglist)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " a = 100 \n", " b = 6 \n", " c = 10 \n", " d = 100\n" ] } ], "source": [ "a,b,c,d = egfunc(eglist)\n", "print ' a =',a,'\\n b =',b,'\\n c =',c,'\\n d =',d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Implicit arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When an argument of a function is common in majority of the cases or it is \"implicit\" this concept is used." ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def implicitadd(x,y=3):\n", " return x+y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**implicitadd( )** is a function accepts two arguments but most of the times the first argument needs to be added just by 3. Hence the second argument is assigned the value 3. Here the second argument is implicit." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now if the second argument is not defined when calling the **implicitadd( )** function then it considered as 3." ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "implicitadd(4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But if the second argument is specified then this value overrides the implicit value assigned to the argument " ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "implicitadd(4,4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Any number of arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If the number of arguments that is to be accepted by a function is not known then a asterisk symbol is used before the argument." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def add_n(*args):\n", " res = 0\n", " reslist = []\n", " for i in args:\n", " reslist.append(i)\n", " print reslist\n", " return sum(reslist)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The above function accepts any number of arguments, defines a list and appends all the arguments into that list and return the sum of all the arguments." ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 5]\n" ] }, { "data": { "text/plain": [ "15" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "add_n(1,2,3,4,5)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n" ] }, { "data": { "text/plain": [ "6" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "add_n(1,2,3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Global and Local Variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Whatever variable is declared inside a function is local variable and outside the function in global variable." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [], "source": [ "eg1 = [1,2,3,4,5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the below function we are appending a element to the declared list inside the function. eg2 variable declared inside the function is a local variable." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def egfunc1():\n", " def thirdfunc(arg1):\n", " eg2 = arg1[:]\n", " eg2.append(6)\n", " print \"This is happening inside the function :\", eg2 \n", " print \"This is happening before the function is called : \", eg1\n", " thirdfunc(eg1)\n", " print \"This is happening outside the function :\", eg1 \n", " print \"Accessing a variable declared inside the function from outside :\" , eg2" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is happening before the function is called : [1, 2, 3, 4, 5]\n", "This is happening inside the function : [1, 2, 3, 4, 5, 6]\n", "This is happening outside the function : [1, 2, 3, 4, 5]\n", "Accessing a variable declared inside the function from outside :" ] }, { "ename": "NameError", "evalue": "global name 'eg2' 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\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0megfunc1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36megfunc1\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0mthirdfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0meg1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0;34m\"This is happening outside the function :\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0meg1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0;34m\"Accessing a variable declared inside the function from outside :\"\u001b[0m \u001b[0;34m,\u001b[0m \u001b[0meg2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: global name 'eg2' is not defined" ] } ], "source": [ "egfunc1()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If a **global** variable is defined as shown in the example below then that variable can be called from anywhere." ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "eg3 = [1,2,3,4,5]" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def egfunc1():\n", " def thirdfunc(arg1):\n", " global eg2\n", " eg2 = arg1[:]\n", " eg2.append(6)\n", " print \"This is happening inside the function :\", eg2 \n", " print \"This is happening before the function is called : \", eg1\n", " thirdfunc(eg1)\n", " print \"This is happening outside the function :\", eg1 \n", " print \"Accessing a variable declared inside the function from outside :\" , eg2" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is happening before the function is called : [1, 2, 3, 4, 5]\n", "This is happening inside the function : [1, 2, 3, 4, 5, 6]\n", "This is happening outside the function : [1, 2, 3, 4, 5]\n", "Accessing a variable declared inside the function from outside : [1, 2, 3, 4, 5, 6]\n" ] } ], "source": [ "egfunc1()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Lambda Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These are small functions which are not defined with any name and carry a single expression whose result is returned. Lambda functions comes very handy when operating with lists. These function are defined by the keyword **lambda** followed by the variables, a colon and the respective expression." ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": true }, "outputs": [], "source": [ "z = lambda x: x * x" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "64" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z(8)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###map" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**map( )** function basically executes the function that is defined to each of the list's element separately." ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": true }, "outputs": [], "source": [ "list1 = [1,2,3,4,5,6,7,8,9]" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, 4, 5, 6, 7, 8, 9, 10, 11]\n" ] } ], "source": [ "eg = map(lambda x:x+2, list1)\n", "print eg" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also add two lists." ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [], "source": [ "list2 = [9,8,7,6,5,4,3,2,1]" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[10, 10, 10, 10, 10, 10, 10, 10, 10]\n" ] } ], "source": [ "eg2 = map(lambda x,y:x+y, list1,list2)\n", "print eg2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Not only lambda function but also other built in functions can also be used." ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['10', '10', '10', '10', '10', '10', '10', '10', '10']\n" ] } ], "source": [ "eg3 = map(str,eg2)\n", "print eg3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###filter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**filter( )** function is used to filter out the values in a list. Note that **filter()** function returns the result in a new list." ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": true }, "outputs": [], "source": [ "list1 = [1,2,3,4,5,6,7,8,9]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To get the elements which are less than 5," ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "filter(lambda x:x<5,list1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice what happens when **map()** is used." ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[True, True, True, True, False, False, False, False, False]" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "map(lambda x:x<5, list1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can conclude that, whatever is returned true in **map( )** function that particular element is returned when **filter( )** function is used." ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[4, 8]" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "filter(lambda x:x%4==0,list1)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }