Pages

Thursday, July 9, 2015

Python – Functions-1

Functions are normally a block of reusable code that is used to perform a specific action. We define them to provide modularity for the application and a high degree of code reusing.

Python also supports functions. In this article we will see how we can create Functions.

Defining a Function

In order to define a function in python, we need to follow some syntax
1) Function blocks begin with  a keyword def followed by function name and Parentheses(:)
          Def functionName():

2) All Parameters or arguments needs to be placed in side the Parentheses.
3) The first line in the function should be a Docstring, which tells us what this function do
4) Code blocks starts after the (:)
5) A statement return [expression] exits a function, optionally passing back an expression to the caller

Example –

>>> def myFucntion():
...     """ This is My Sample Function Doc String"""
...     print "this is Sample Function"
...

>>> myFucntion()
this is Sample Function

The above example creates a Sample Function myFunction(). The invocation of the function is done by calling the Function Name directly.

Function with Arguments
Function with arguments or parameters. Parameters have a positional behavior and you need to inform them in the same order that they were defined

>>> def printMe(str):
...     print str
...
>>> printMe("jagadish")
jagadish

>>> printMe(str = "Hello")
Hello

Pass by Reference or Value
One important thing to understand in here is Python pass parameter by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.

>>> def ChangeMe(myList):
...     myList.append([1,2,3])
...     print myList
...     return
...
>>> myList = [10,20,30];
>>> ChangeMe(myList)
[10, 20, 30, [1, 2, 3]]
>>> print myList
[10, 20, 30, [1, 2, 3]]


So when we check the values, we see that myList has been changed when printed in both cases.

No comments :

Post a Comment