Modules in Python

To create a Modules in Python, you use the def keyword, followed by the function name and argument list, and a colon to begin the function body.

General Syntax :

def (argument_list):
....}=> Body

P.S : Indentation must be taken care


Ok , now lets see few eliminator examples of modules .

import sys

def main():
print "\nTill which level do you want to see the sequence ? "
n = int(sys.stdin.readline()) # read from the user
fibonacci(n) # call to the method with parameter


def fibonacci(n):
a,b = 0,1
for i in range(0,n):
print a
a,b, = b,a+b

if __name__ == '__main__':
main()

Here the main method , calls the Fibonacci method , which prints the sequence of Fibonacci numbers.


A method can "RETURN" ?

As
Python passes all arguments using "pass by reference" , the changes on the arguments in the method is always reflected on them .

A module can return an kind of data types , those which we had seen in the earlier post .

Keeping this in mind , here a small code which everything clear :
a, b, c = 0, 0, 0
def Giveabc():
a = "Hello"
b = "Python"
c = "!"
return a,b,c #defines a tuple on the fly

def GiveTuple():
a,b,c = 1,2,3
return (a,b,c)

def GiveList():
a,b,c = (3,4),(4,5),(5,6)
return [a,b,c]

a,b,c = Giveabc():
d,e,f = GiveTuple():
g,h,i = GiveList():

Different variations can be used to return what is required, based on our need :)


Lambda Expressions (Anonymous Functions) !!!

"In Python you can define a one-line mini-functions on the fly.
Borrowed from Lisp, these so-called lambda functions can be used anywhere a function is required."

The below is an wonderful example from the book "Dive Into Python".

>>>
def f(x):
... return x*2
...
>>> f(3)
6
>>> g = lambda x: x*2
>>> g(3)
6
>>> (lambda x: x*2)(3)
6


This is a lambda function that accomplishes the same thing as the normal function above it. Note the abbreviated syntax here: there are no parentheses around the argument list, and the return keyword is missing (it is implied, since the entire function can only be one expression). Also, the function has no name, but it can be called through the variable it is assigned to.

You can use a lambda function without even assigning it to a variable. This may not be the most useful thing in the world, but it just goes to show that a lambda is just an in-line function.

I had to borrow it from there because, this is the best way we can know how lambda function can be really useful for us , in a simple one-line.






Share this