Linux

Python Function

You have seen several built-in function in python like len(), range() and cmp(). if you want to create own function, Python lets you to create own functions. So what is the advantage of creating own function ? well Function allows you to break up your long program into magangeable blocks, Easy to maintain and reuse. It eliminate redundancy. As we go further you will get to know the advantages of function.

Defining a Python function

In python , very simple rule to define a function. Syntax
def function_name(arguments):
	code 
	return value
Calling a Python function
 function_name() 
Calling a Python function like same calling the built-in function. Use the name of the function followed by set of parentheses. So i can call this function many time with same or different arguments. You can execute it by calling it from another Python function. So in this way i can say function reduce the size of code as well as reduce redundancy.
let's learn from example.
def hello():
   """ This is Hello program"""
   print "You are in Hello"

hello()
Out-put
Python hello function
hello function
Above program is very simple just define hello() function. The line def hello(): and its block are a Python function definition. They define what the function does, but don't run. It will not run the function untill it sees a function call for it. Consider you want to document the function. Functions have special mechanism that allow you to document them. That is called docstring.

Function with arguments

As you've seen with built-in function, like len() function, you pass the sequence and the function return its length. Your own Python function also receive and return arguments. . When you use keyword arguments in a Python function call, the caller identifies the arguments by the parameter name. This allows you to place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
Let us discuss our example
def fun1(str1):
   print str1
str1 = "hello all"
fun1(str1)
Out-put
Python hello function with arguments
hello function with argument
In above program argument "str" has been passed by calling Python function. The string str is printed with in the function. Consider a case when argument is not passed what happen ? Next example will clear the picture.
Python function showing error, argument not passed
Showing error in function

Python Function with the argument and return value

Consider a Python function with return value is small department where some material goes and new processed material comes out.
Let us discuss next example
def sum(a, b):
   c = a+b
   return c
x = 10
y = 50
print "Send x and y to sum department"
print "value of addition ", sum(x,y)
In above example print statement is outside from the function. Print statement print the function sum(x,y) , so what is the value of sum(x,y) ? As function return c , that is the value of function.
Out-put
Python function with return value
Function with return value

Python function with default Argument

If you don't provide value to argument then the function take its default value defined in the function. Our next example will clear all the doubt.
def info(name, age=50):
   print "Name", name
   print "age", age
info("mohit", age=28)
info("Ravi")
Out-put
Python function showing default value
Showing default argument

Python function with Variable-length arguments

Sometime you need to pass more arguments than you specified while defining the Python function. These type of arguments are called variable-length arguments.
Syntax
def  function_name(arg, *vartuple):
	code block
	return 
Let's discuss our next example
def variable( agr1, *vari):
   print "Out-put is",agr1
   for var in vari:
       print var
variable(6)
variable(90,9,4,5,6)
Out-out
Python function with variable length arguments
function with variable_length
From output we deduce that first argument is handled by argument arg1 rest arguments are handled by argument *vari .

keyworded variable length of arguments

Consider a situation, when you want to pass argument as "key=value" format. See the example below.
Python function with dictionary kwarg**
Python function with dictionary
Click to view code


Argument Pass by reference or value

Call by reference means passing the address of a variable where the actual value is stored. All arguments in the Python language are passed by reference. The called Python function uses the value stored in the passed address; any changes to it do affect the source variable.
Example
def ref(list1):
   list1.extend([23,89])
   print "list inside the function: ",list1
list1 = [12,67,90]
print "list before pass", list1
ref(list1)
print "list outside the function", list1
Let's check the output with code
Python function call by reference
call by reference
List extends inside the Python function but the change also reflected back in the calling function.
Another Example
def fun(a):
   a=a+4
   print "Inside the function", a
a= 10
fun(a)
print "Outside the function", a
Out-put
python function call by reference
call by reference
After seeing above example you think it is the example of call by value because change inside the Python function did not reflect back to calling function. At this situation still I would say it is call by reference because inside the function I made new assignment that is a= a+4 . We imagine that a = a + 4 is changing the number stored in a, but it's really reassigning a to point to a new object

Scope of Variables

You may not access all variables of program from all locations. This depends upon where a variable has been declared. There are two basic scopes of variables in Python:
  1. Local variables
  2. Global variables
Local variable is defined inside the Python function. Local variables are only accessible with in their local scope.
Global varible is defined outside the Python function. Global variables are only accessible throughout the program.
Variable a is global variable its value remain same outside the function and inside the function. But if you reassign a inside the function ? Let us discuss with example
def fun():
   a =12
   print "Inside the function", a
a= 10
fun()
print "Outside a",a
Let us check out put with pictorial diagram.
Python Global variable reassigning in local
Global reassigning in local
If you reassign global variable inside the function it does not reflect outside the Python function If local variable is accessed outside the function.
Let us discuss in next example
def fun():
   a =12
   print "a inside the function",a
fun()
print "Outside a",a
Out-put
Local Variable accessing outside the Python function
Local variable accessing from outside the function
It give error if you access local variable from outside the function. Consider a situation when you feel that change inside the function should reflect outside the Python function. In this situation you would explicit define global keyword as shown in example below.
def ref():
   global k
   k=k+7
   print k
k=10
ref()
print "k outside ",k
Out-put
Python global variable
global variable
In above example after calling function value of k changed because inside the function k is defined as gloabal variable. The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.




admin