14. Python -Functions• A function is a block of organized, reusable code that is used toperform a single, related action. Functions provides better modularityfor your application and a high degree of code reusing.• As you already know, Python gives you many built-in functions likeprint() etc. but you can also create your own functions. These functionsare called user-defined functions.
2.
Defining a FunctionHereare simple rules to define a function in Python:• Function blocks begin with the keyword def followed by the functionname and parentheses ( ( ) ).• Any input parameters or arguments should be placed within theseparentheses. You can also define parameters inside theseparentheses.• The first statement of a function can be an optional statement - thedocumentation string of the function or docstring.• The code block within every function starts with a colon (:) and isindented.• The statement return [expression] exits a function, optionally passingback an expression to the caller. A return statement with noarguments is the same as return None.• Syntax:• def functionname( parameters ):• "function_docstring" function_suite return [expression]
3.
• Syntax:def functionname(parameters ):"function_docstring"function_suitereturn [expression]By default, parameters have a positional behavior, and you needto inform them in the same order that they were defined.• Example:def printme( str ):"This prints a passed string function"print strreturn
4.
Calling a Function•Following is the example to call printme() function:def printme( str ): "This is a print function“print str;return;printme("I'm first call to user defined function!");printme("Again second call to the same function");• This would produce following result:I'm first call to user defined function!Again second call to the same function
5.
Pass by referencevs valueAll parameters (arguments) in the Python language are passed byreference. It means if you change what a parameter refers to within afunction, the change also reflects back in the calling function. Forexample:def changeme( mylist ): "This changes a passed list“mylist.append([1,2,3,4]);print "Values inside the function: ", mylistreturnmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist• So this would produce following result:Values inside the function: [10, 20, 30, [1, 2, 3, 4]]Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
6.
There is onemore example where argument is being passed by reference butinside the function, but the reference is being over-written.def changeme( mylist ): "This changes a passed list"mylist = [1,2,3,4];print "Values inside the function: ", mylistreturnmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist• The parameter mylist is local to the function changeme. Changing mylistwithin the function does not affect mylist. The function accomplishesnothing and finally this would produce following result:Values inside the function: [1, 2, 3, 4]Values outside the function: [10, 20, 30]
7.
Function Arguments:A functionby using the following types of formal arguments::– Required arguments– Keyword arguments– Default arguments– Variable-length argumentsRequired arguments:• Required arguments are the arguments passed to a function in correctpositional order.def printme( str ): "This prints a passed string"print str;return;printme();• This would produce following result:Traceback (most recent call last):File "test.py", line 11, in <module> printme();TypeError: printme() takes exactly 1 argument (0 given)
8.
Keyword arguments:• Keywordarguments are related to the function calls. When youuse keyword arguments in a function call, the caller identifiesthe arguments by the parameter name.• This allows you to skip arguments or place them out of orderbecause the Python interpreter is able to use the keywordsprovided to match the values with parameters.def printme( str ): "This prints a passed string"print str;return;printme( str = "My string");• This would produce following result:My string
9.
Following example givesmore clear picture. Note, here order ofthe parameter does not matter:def printinfo( name, age ): "Test function"print "Name: ", name;print "Age ", age;return;printinfo( age=50, name="miki" );• This would produce following result:Name: miki Age 50
10.
Default arguments:• Adefault argument is an argument that assumes a defaultvalue if a value is not provided in the function call for thatargument.• Following example gives idea on default arguments, it wouldprint default age if it is not passed:def printinfo( name, age = 35 ): “Test function"print "Name: ", name;print "Age ", age;return;printinfo( age=50, name="miki" );printinfo( name="miki" );• This would produce following result:Name: miki Age 50 Name: miki Age 35
11.
Variable-length arguments:• Youmay need to process a function for more arguments thanyou specified while defining the function. These arguments arecalled variable-length arguments and are not named in thefunction definition, unlike required and default arguments.• The general syntax for a function with non-keyword variablearguments is this:def functionname([formal_args,] *var_args_tuple ):"function_docstring"function_suitereturn [expression]
12.
• An asterisk(*) is placed before the variable name that will hold thevalues of all nonkeyword variable arguments. This tuple remainsempty if no additional arguments are specified during the functioncall. For example:def printinfo( arg1, *vartuple ):"This is test"print "Output is: "print arg1for var in vartuple:print varreturn;printinfo( 10 );printinfo( 70, 60, 50 );• This would produce following result:Output is:10Output is:706050
13.
The Anonymous Functions:Youcan use the lambda keyword to create small anonymous functions.These functions are called anonymous because they are not declaredin the standard manner by using the def keyword.• Lambda forms can take any number of arguments but return just onevalue in the form of an expression. They cannot contain commands ormultiple expressions.• An anonymous function cannot be a direct call to print becauselambda requires an expression.• Lambda functions have their own local namespace and cannot accessvariables other than those in their parameter list and those in theglobal namespace.• Although it appears that lambda's are a one-line version of a function,they are not equivalent to inline statements in C or C++, whosepurpose is by passing function stack allocation during invocation forperformance reasons.• Syntax:lambda [arg1 [,arg2,.....argn]]:expression
14.
Example:• Following isthe example to show how lembda form of functionworks:sum = lambda arg1, arg2: arg1 + arg2;print "Value of total : ", sum( 10, 20 )print "Value of total : ", sum( 20, 20 )• This would produce following result:Value of total : 30Value of total : 40
15.
Scope of Variables:•All variables in a program may not be accessible at all locations in thatprogram. This depends on where you have declared a variable.• The scope of a variable determines the portion of the program whereyou can access a particular identifier. There are two basic scopes ofvariables in Python:Global variablesLocal variables• Global vs. Local variables:• Variables that are defined inside a function body have a local scope,and those defined outside have a global scope.• This means that local variables can be accessed only inside thefunction in which they are declared whereas global variables can beaccessed throughout the program body by all functions. When you calla function, the variables declared inside it are brought into scope.
16.
• Example:total =0; # This is global variable.def sum( arg1, arg2 ):"Add both the parameters"total = arg1 + arg2;print "Inside the function local total : ", totalreturn total;# Now you can call sum functionsum( 10, 20 );print "Outside the function global total : ", total• This would produce following result:Inside the function local total : 30Outside the function global total : 0