PYTHON PROGRAMMING (2010)

Python functions

·        These function block with key words and followed by parenthesis.

·        Input should position between theses parenthesis.

·        First statement might be or can be optional statements.

·        Every function code block starts with semi colon (:).

·        It is optional passing back function to the user.

Syntax

def functionname( parameters ):

"function_docstring"

function_suite

return [expression].

Example

def printme( str ):

"This prints a passed string into this function"

print str

return.

Calling of a function

Declaring function gives it a name, specifies the parameters which are to be included in the function as well as structures of the blocks of that of the code. When the basic structure of a function is decided, one can execute it just by calling it from another function or even by just directly from the Python prompt.

Example

#!/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");

Output

I'm first call to user defined function!

Again second call to the same function

Pass by reference vs. the value

In python all the parameter are passed by through references. Parameters are refereed within the function and the therefore the changes also reflects back the calling functions.

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

Output

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]

Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is various another kinds where the arguments are passed within the functions. And usual the reference is overwritten inside the function.

Example

#!/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 assign 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

Output

Values inside the function: [1, 2, 3, 4]

Values outside the function: [10, 20, 30]

Image