Python Functions

A function is a block of org anized, reusable code that is used to perform a sing le, related action. Functions provide better modularity for your application and a hig h deg ree of code reusing . As you already know, Python g ives you many built-in functions like print(), etc. but you can also create your own functions. T hese functions are called user-defined functions. Defining a Function You can define functions to provide the required functionality. Here are simple rules to define a function in Python. Function blocks beg in with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arg uments should be placed within these parentheses. You can also define parameters inside these parentheses. T he first statement of a function can be an optional statement - the documentation string of the function or docstring. T he code block within every function starts with a colon (:) and is indented. T he statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arg uments is the same as return None. Syntax: def functionname( parameters ): "function_docstring" function_suite return [expression] By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. Example: Here is the simplest form of a Python function. T his function takes a string as input parameter and prints it on standard screen. def printme( str ): "This prints a passed string into this function" print str return Calling a Function Defining a function only g ives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function: #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str; return; # Now you can call printme function printme("I'm first call to user defined function!"); printme("Again second call to the same function"); When the above code is executed, it produces the following result: I'm first call to user defined function! Again second call to the same function Pass by reference vs value All parameters (arg uments) in the Python lang uag e are passed by reference. It means if you chang e what a parameter refers to within a function, the chang e also reflects back in the calling function. For example: #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result: Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] T here is one more example where arg ument is being passed by reference and the reference is being overwritten inside the called function. #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist T he parameter mylist is local to the function chang eme. Chang ing mylist within the function does not affect mylist. T he function accomplishes nothing and finally this would produce the following result: Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30] Function Arg uments: You can call a function by using the following types of formal arg uments: Required arg uments Keyword arg uments Default arg uments Variable-leng th arg uments Required arg uments: Required arg uments are the arg uments passed to a function in correct positional order. Here, the number of arg uments in the function call should match exactly with the function definition. T o call the function printme(), you definitely need to pass one arg ument, otherwise it would g ive a syntax error as follows: #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str; return; # Now you can call printme function printme(); When the above code is executed, it produces the following result: Traceback (most recent call last): File "test.py", line 11, in printme(); TypeError: printme() takes exactly 1 argument (0 given) Keyword arg uments: Keyword arg uments are related to the function calls. When you use keyword arg uments in a function call, the caller identifies the arg uments by the parameter name. T his allows you to skip arg uments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways: #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str; return; # Now you can call printme function printme( str = "My string"); When the above code is executed, it produces the following result: My string Following example g ives more clear picture. Note, here order of the parameter does not matter. #!/usr/bin/python # Function definition is here def printinfo( name, age ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return; # Now you can call printinfo function printinfo( age=50, name="miki" ); When the above code is executed, it produces the following result: Name: miki Age 50 Default arg uments: A default arg ument is an arg ument that assumes a default value if a value is not provided in the function call for that arg ument. Following example g ives an idea on default arg uments, it would print default ag e if it is not passed: #!/usr/bin/python # Function definition is here def printinfo( name, age = 35 ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return; # Now you can call printinfo function printinfo( age=50, name="miki" ); printinfo( name="miki" ); When the above code is executed, it produces the following result: Name: miki Age 50 Name: miki Age 35 Variable-leng th arg uments: You may need to process a function for more arg uments than you specified while defining the function. T hese arg uments are called variable-length arg uments and are not named in the function definition, unlike required and default arg uments. T he g eneral syntax for a function with non-keyword variable arg uments is this: def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression] An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arg uments. T his tuple remains empty if no additional arg uments are specified during the function call. Following is a simple example: #!/usr/bin/python # Function definition is here def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return; # Now you can call printinfo function printinfo( 10 ); printinfo( 70, 60, 50 ); When the above code is executed, it produces the following result: Output is: 10 Output is: 70 60 50 The Anonymous Functions: You can use the lambda keyword to create small anonymous functions. T hese functions are called anonymous because they are not declared in the standard manner by using the def keyword. Lambda forms can take any number of arg uments but return just one value in the form of an expression. T hey cannot contain commands or multiple expressions. An anonymous function cannot be a direct call to print because lambda requires an expression. Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the g lobal namespace. Althoug h it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons. Syntax: T he syntax of lambda functions contains only a sing le statement, which is as follows: lambda [arg1 [,arg2,.....argn]]:expression Following is the example to show how lambda form of function works: #!/usr/bin/python # Function definition is here sum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) When the above code is executed, it produces the following result: Value of total : Value of total : 30 40 The return Statement: T he statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arg uments is the same as return None. All the above examples are not returning any value, but if you like you can return a value from a function as follows: #!/usr/bin/python # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total; # Now you can call sum function total = sum( 10, 20 ); print "Outside the function : ", total When the above code is executed, it produces the following result: Inside the function : 30 Outside the function : 30 Scope of Variables: All variables in a prog ram may not be accessible at all locations in that prog ram. T his depends on where you have declared a variable. T he scope of a variable determines the portion of the prog ram where you can access a particular identifier. T here are two basic scopes of variables in Python: Global variables Local variables Global vs. Local variables: Variables that are defined inside a function body have a local scope, and those defined outside have a g lobal scope. T his means that local variables can be accessed only inside the function in which they are declared, whereas g lobal variables can be accessed throug hout the prog ram body by all functions. When you call a function, the variables declared inside it are broug ht into scope. Following is a simple example: #!/usr/bin/python total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total When the above code is executed, it produces the following result: Inside the function local total : 30 Outside the function global total : 0

Comments