Skip to main content

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?

Comments

Popular posts from this blog

Python Interview Questions -Coding Snipets

 This post is dedicated for all DevOps Engineer, Software Engineers who are preparing for Coding Interviews,  Overview of Coding Interviews Most Companies looking for People with minimum Coding knowledge. In a coding interview, you will be given a small problem to solve within 10 - 20 minutes online screen or in-person on their system. In the question, you might be having some part of the code framed and you might be asked to write a snippet of code in between. You need to understand the code comments and proceed to build the expected snippet of code. Bigger companies look for the General purpose questions, where small companies look for specific questions. The General questions would be like this: Determine if the given word is a palindrome or not. (Example madam) Determine given number is prime or not. How to prepare for a coding interview? Now we have the flexibility to choose the programming language on which you are comfortable.  In general DevOps Infra guys will be ...

Python Sets and Dictionaries

Python Sets Python Maps examples A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. Dictionaries consist of pairs (called items) of keys and their corresponding values. Dictionaries can be created by placing a comma-separated list of key: value pairs within curly braces Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Python Set Operations and methods Python Set methods continueed >>> SET={'new','old','list','new'} >>> SET set(['new', 'old', 'list']) Lets play with set operations, it is more like school math here... >>> s={1,2,3,4} >>> k={3,4,5,6} >>> len(s) 4 >>> len(k) 4 >>> 1 in s True >>...

Program Controls and loops in Python

Python Programming controls The flow of program will be controlled with conditional statements where this flow  if condition if-else condition if-elif condition while loop while - else loop for loop for with if- else loop if condition Here I would like to work on program control statements, wherein relate some operating system functionalities so that, this would give some basic prototype for the sys admin scripts. #!/usr/bin/python # This illustrate if condition # Filename : ifex.py import os d=os.listdir('/home/pavanbsd/pybin') print d f='ifex.py' if f in d: print "File exists" else: print "Not found..." if-elif-else ladder No worries, coming soon... When you need the task that need to be done repeatedly then your choice is using loops. Python provides two simple loop constructs easy to use! More powerful then other scripting compare to, it has 'else' block. while loop Understand the power of while loop,...