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 .
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 :
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".
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.
General Syntax :
def (argument_list):
....}=> Body
P.S : Indentation must be taken care
Ok , now lets see few eliminator examples of modules .
Here the main method , calls the Fibonacci method , which prints the sequence of Fibonacci numbers.
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()
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"In Python you can define a one-line mini-functions on the fly.
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) !!!
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.
Recent blog posts
- watir-webdriver web inspector
- gem list to gemfile
- Packing ruby2.0 on debian.
- Made it into The Guinness Book!
- to_h in ruby 2.0
- Filter elements by pattern jQuery.
- Better HTML password fields for mobile ?
- Grayscale image when user offline
- nth-child CSS pseudo-class Christmas colors
- EventEmitter in nodejs