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,1for i in range(0,n):print aa,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, 0def Giveabc():a = "Hello"b = "Python"c = "!"return a,b,c #defines a tuple on the fly def GiveTuple():a,b,c = 1,2,3return (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 needLambda 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
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.