Showing posts with label lambda function example. Show all posts
Showing posts with label lambda function example. Show all posts

Monday, July 14, 2014

Functions in Python


Heere we have experimenting with functions in Python, Functions can be defined for specific task, functions are prepared to reuse them. modular programming can be defined as breaking the bigger task into chunks of blocks this can be achived with the Python functions. Over all we are going to know in depth knowledge on how Python function is powerful then other structure programs.

We have seen some built-in functions which you don't need to import any modules.

  • str(), int(), float(), bool() -- type definitions
  • type(), id(), dir() --  introspecting the functions
  • len(), range() -- sequance collection related functions
  • print(), input(), raw_input() -- input output functions
Python Function overview
  1. Function definition 
  2. Calling Function in assignment
  3. Adding DocString to Function 
  4. Function Execution – Scope of variables
  5. The import and reload
  6. Defining inner functions
  7. Lambda functions

Function definition structure

1. Procedure - which do not have return statement
2. Function - which returns
3. Method - with in a class
4. Module - with in a py file

Defining Function in Python
Function Arguments
In Python we can create function without arguments. We can create with simple arguments with Python object types. We can also assign value for these arguments when calling function is not passed all required arguments then it will use thhese default arguments.

Functions returns
Like other programming languages Python also have 'return' keyword to send back the result of the task from the function. Function is a sub program it follows single entry and single exit. This return statement will be the last exiting statement, You may have multiple returns in a function only where that can be under certain conditional expressions. That means it will be in if-else blocks.

Function Calling
The function which has return statement such functions can be called in :

  1. assignment 
  2. expression
  3. output 

The following function example shows all the above variations.
#!/usr/bin/python

def add(x=10,y=1):
        return x+y
def printline():
        "This is procedure "
        print '#'*25
print "I'm in main now"

# Function call in an expression
x=add(100,3)+30
print "Expression       :", x

# Function call in assignment
y=add(50,50)
print "Assignment       :",y

# Function call in output
print "Output           :", add(200,300)
print "Default arguments:", add()
print "Partial arguments:", add(y=20)

# Procedure call
printline()



Lambda functions

The lambda function are inline functions, which don't have to define with 'def'. Here we define the function with 'lambda' keyword. These functions don't have any name, they are anonymus functions. These lamdda functions are useful when you have simple logic where it can be return output with a condition or a loop. Remember that, we cannot use it for complex logics with Lambda functions. Defining lambda syntax:
variable = lambda args : expression
Lambda fuction example:
#!/usr/bin/python

# Lambda function definition
m=lambda k: str(k/1024.0)+' MB'

# Calling function
print "m(204800):", m(204800)

g=lambda k: str(k/(1024*1024.0))+' GB'

print "G(40960000):", g(40960000)
The execution of lambda function as follows:
m(204800): 200.0 MB
G(40960000): 39.0625 GB
Lets try to build the script with more specific to system admin commands.
#!/usr/bin/python

import commands

prints=lambda:'#'*45

def checkDiskspace():
        """This function display diskspace usage"""
        print prints()
        d=commands.getoutput("df -h|grep dev")
        print d

def checkMem():
        "Checks free memory"
        print prints()
        m=commands.getoutput("free -m")
        print m

def checkCPULoad():
        "Checks load averages"
        print prints()
        c=commands.getoutput("uptime")
        print c

print "===main===="
checkDiskspace()
checkCPULoad()
checkMem()
print prints()


The output would be as follows:
pavanbsd@puppet:~/pybin$ ./utilfun.py
===main====
#############################################
df: `/var/lib/lightdm/.gvfs': Permission denied
/dev/sda1       6.8G  5.7G  825M  88% /
udev            1.8G  4.0K  1.8G   1% /dev
/dev/sdb5        21G   44M   20G   1% /tmp
/dev/sdc1       9.8G   23M  9.2G   1% /app
/dev/sr1        706M  706M     0 100% /media/Ubuntu 12.04.3 LTS i386
/dev/sr0         23M   23M     0 100% /media/VBOXADDITIONS_4.2.4_81684
#############################################
 12:11:56 up 1 day,  5:09,  1 user,  load average: 0.06, 0.08, 0.12
#############################################
             total       used       free     shared    buffers     cached
Mem:          3500       1622       1878          0         67       1407
-/+ buffers/cache:        147       3352
Swap:         1022          0       1022
#############################################
Here I have learned about positional arguments simple sentences I can say that:

 *args = list of arguments -as positional arguments
**kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.

The syntax is the * and ** prefixing the argument, the names *args and **kwargs are only by convention but there's no hard requirement to use them.

Why *args, **args used?
*args and **kwargs are special-magic features of Python and they are not operators symbols in this context.
You would use *args when you're calling a function not sure how many arguments might be passed to the function, i.e. it allows you pass an arbitrary number of arguments to your function.

#!/usr/bin/env python
"""
Simple example of keyword arguments
With multiple ways to call the function
"""
def demo(**args):
    print args

demo()

demo(name='Pavan', gender='male', age=42)

d  = {'color' : 'BlueYellow', 'value':'+3v', 'make':'INDIA', 'version': 'v0.0.1'}

# here ** unpacking dictionaries
demo(**d)

The execution gives us:
~/pybin$ ./kwargs.py
{}
{'gender': 'male', 'age': 42, 'name': 'Pavan'}
{'color': 'BlueYellow', 'make': 'INDIA', 'version': 'v0.0.1', 'value': '+3v'}

You can call the ** args many ways here it is using for passing local list, Passing positional values with its name is more fun.

n_times = 10000
mycourse='Python Orientation'
mytraining = 'Vybhava Technologies!'
print "{mycourse} at {mytraining}  is experimenting is {n_times}x joy!".format(**locals())
>>> execfile('c:/pybin/kwargsex.py')

Python Orientation at Vybhava Technologies!  is experimenting is 10000x joy!

Differences between Python Procedure and Functions.
Differences between funciton module and Method
Differences between function and operator overloading
What is method overloading? What is method overriding?
How to import module in Python?

DevOps Foundation course

DevOps Foundation course
Join us to learn DevOps from the Beginning