Sunday, July 12, 2015

Python – Functions -2

In this series of the Python functions we will see the types of function arguments.

Function arguments in python can be passed using

Required arguments - Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

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

Keyword arguments - Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

>>> def printMe(str):
...     print str
>>> printMe(str = "Hello")

Default arguments - A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument

>>> def changeMe(name,age=20):
...     print name,age

>>> changeMe("jagadish")
jagadish 20

The default argument age is taken a value of 20 by default.

Variable length arguments – The Most important one and most used one is the variable length argument type. There are some times while programming where we need to process variable number of arguments. We are not sure how many arguments will be passed during execution.

Python provides a way to process variable number of arguments by using *argument in the function definition

The function definition of a variable argument function looks as,
def functionname([formal_args,] *var_args_tuple ):

We can see that a asterisk (*) is placed before the argument name to tell that it’s a variable length.

Lets see an Example of the variable length argument,

>>> def printMe(arg1,*var):
...     print arg1
...     for x in var:
...             print x

>>> printMe("jagadish",10,20,30)

We can see the second argument to the function is *var which tells python that multiple values may occur during execution.

Anonymous Functions
Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". 

One important thing to remember is that Lambda does not include a return statement since it’s an expression that is retuned.

The general format for lambda form is:
lambda parameter(s): expression using the parameter(s)

An example will be,

>>> k= lambda y: y + y
>>> k(30)
>>> k(40)

No comments :

Post a Comment