Functions
Functions
Functions
1. Built in Functions
2. User Defined Functions
1. Built in Functions:
The functions which are coming along with Python software automatically,are called built
in functions or pre defined functions
Eg:
id()
type()
input()
eval()
etc..
def function_name(parameters) :
""" doc string"""
----
-----
return value
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
1 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: While creating functions we can use 2 keywords
1. def (mandatory)
2. return (optional)
test.py:
1) def wish():
2) print("Hello Good Morning")
3) wish()
4) wish()
5) wish()
Parameters
Parameters are inputs to the function. If a function contains parameters,then at the time
of calling,compulsory we should provide values otherwise,otherwise we will get error.
Eg: Write a function to take name of the student as input and print wish message by
name.
1. def wish(name):
2. print("Hello",name," Good Morning")
3. wish("Durga")
4. wish("Ravi")
5.
6.
7. D:\Python_classes>py test.py
8. Hello Durga Good Morning
9. Hello Ravi Good Morning
Eg: Write a function to take number as input and print its square value
1. def squareIt(number):
2. print("The Square of",number,"is", number*number)
3. squareIt(4)
4. squareIt(5)
5.
6. D:\Python_classes>py test.py
7. The Square of 4 is 16
8. The Square of 5 is 25
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
2 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Return Statement:
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.
1. def add(x,y):
2. return x+y
3. result=add(10,20)
4. print("The sum is",result)
5. print("The sum is",add(100,200))
6.
7.
8. D:\Python_classes>py test.py
9. The sum is 30
10. The sum is 300
If we are not writing return statement then default return value is None
Eg:
1. def f1():
2. print("Hello")
3. f1()
4. print(f1())
5.
6. Output
7. Hello
8. Hello
9. None
1. def even_odd(num):
2. if num%2==0:
3. print(num,"is Even Number")
4. else:
5. print(num,"is Odd Number")
6. even_odd(10)
7. even_odd(15)
8.
9. Output
10. D:\Python_classes>py test.py
11. 10 is Even Number
12. 15 is Odd Number
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
3 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q. Write a function to find factorial of given number?
1) def fact(num):
2) result=1
3) while num>=1:
4) result=result*num
5) num=num-1
6) return result
7) for i in range(1,5):
8) print("The Factorial of",i,"is :",fact(i))
9)
10) Output
11) D:\Python_classes>py test.py
12) The Factorial of 1 is : 1
13) The Factorial of 2 is : 2
14) The Factorial of 3 is : 6
15) The Factorial of 4 is : 24
Eg 1:
1) def sum_sub(a,b):
2) sum=a+b
3) sub=a-b
4) return sum,sub
5) x,y=sum_sub(100,50)
6) print("The Sum is :",x)
7) print("The Subtraction is :",y)
8)
9) Output
10) The Sum is : 150
11) The Subtraction is : 50
Eg 2:
1) def calc(a,b):
2) sum=a+b
3) sub=a-b
4) mul=a*b
5) div=a/b
6) return sum,sub,mul,div
7) t=calc(100,50)
8) print("The Results are")
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
4 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
9) for i in t:
10) print(i)
11)
12) Output
13) The Results are
14) 150
15) 50
16) 5000
17) 2.0
Types of arguments
def f1(a,b):
------
------
------
f1(10,20)
1. positional arguments
2. keyword arguments
3. default arguments
4. Variable length arguments
1. positional arguments:
def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)
The number of arguments and position of arguments must be matched. If we change the
order then result may be changed.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
5 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2. keyword arguments:
Eg:
1. def wish(name,msg):
2. print("Hello",name,msg)
3. wish(name="Durga",msg="Good Morning")
4. wish(msg="Good Morning",name="Durga")
5.
6. Output
7. Hello Durga Good Morning
8. Hello Durga Good Morning
Here the order of arguments is not important but number of arguments must be matched.
Note:
We can use both positional and keyword arguments simultaneously. But first we have to
take positional arguments and then keyword arguments,otherwise we will get
syntaxerror.
def wish(name,msg):
print("Hello",name,msg)
wish("Durga","GoodMorning") ==>valid
wish("Durga",msg="GoodMorning") ==>valid
wish(name="Durga","GoodMorning") ==>invalid
SyntaxError: positional argument follows keyword argument
3. Default Arguments:
Eg:
1) def wish(name="Guest"):
2) print("Hello",name,"Good Morning")
3)
4) wish("Durga")
5) wish()
6)
7) Output
8) Hello Durga Good Morning
9) Hello Guest Good Morning
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
6 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
If we are not passing any name then only default value will be considered.
***Note:
def f1(*n):
We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.
Eg:
1) def sum(*n):
2) total=0
3) for n1 in n:
4) total=total+n1
5) print("The Sum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)
11)
12) Output
13) The Sum= 0
14) The Sum= 10
15) The Sum= 30
16) The Sum= 100
Note:
We can mix variable length arguments with positional arguments.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
1) def f1(n1,*s):
2) print(n1)
3) for s1 in s:
4) print(s1)
5)
6) f1(10)
7) f1(10,20,30,40)
8) f1(10,"A",30,"B")
9)
10) Output
11) 10
12) 10
13) 20
14) 30
15) 40
16) 10
17) A
18) 30
19) B
Note: After variable length argument,if we are taking any other arguments then we
should provide values as keyword arguments.
Eg:
1) def f1(*s,n1):
2) for s1 in s:
3) print(s1)
4) print(n1)
5)
6) f1("A","B",n1=10)
7) Output
8) A
9) B
10) 10
f1("A","B",10) ==>Invalid
TypeError: f1() missing 1 required keyword-only argument: 'n1'
def f1(**n):
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
8 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
We can call this function by passing any number of keyword arguments. Internally these
keyword arguments will be stored inside a dictionary.
Eg:
1) def display(**kwargs):
2) for k,v in kwargs.items():
3) print(k,"=",v)
4) display(n1=10,n2=20,n3=30)
5) display(rno=100,name="Durga",marks=70,subject="Java")
6)
7) Output
8) n1 = 10
9) n2 = 20
10) n3 = 30
11) rno = 100
12) name = Durga
13) marks = 70
14) subject = Java
Case Study:
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
1. f(3,2) ==> 3 2 4 8
2. f(10,20,30,40) ===>10 20 30 40
4. f(arg4=2,arg1=3,arg2=4)===>3 4 4 2
5. f()===>Invalid
TypeError: f() missing 2 required positional arguments: 'arg1' and 'arg2'
6. f(arg3=10,arg4=20,30,40) ==>Invalid
SyntaxError: positional argument follows keyword argument
[After keyword arguments we should not take positional arguments]
7. f(4,5,arg2=6)==>Invalid
TypeError: f() got multiple values for argument 'arg2'
8. f(4,5,arg3=5,arg5=6)==>Invalid
TypeError: f() got an unexpected keyword argument 'arg5'
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
9 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: Function vs Module vs Library:
Library Function
Types of Variables
Python supports 2 types of variables.
1. Global Variables
2. Local Variables
1. Global Variables
The variables which are declared outside of function are called global variables.
These variables can be accessed in all functions of that module.
Eg:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
10 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2. Local Variables:
The variables which are declared inside a function are called local variables.
Local variables are available only for the function in which we declared it.i.e from outside
of function we cannot access.
Eg:
1) def f1():
2) a=10
3) print(a) # valid
4)
5) def f2():
6) print(a) #invalid
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined
global keyword:
We can use global keyword for the following 2 purposes:
Eg 1:
1) a=10
2) def f1():
3) a=777
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)
12) Output
13) 777
14) 10
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
11 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 2:
1) a=10
2) def f1():
3) global a
4) a=777
5) print(a)
6)
7) def f2():
8) print(a)
9)
10) f1()
11) f2()
12)
13) Output
14) 777
15) 777
Eg 3:
1) def f1():
2) a=10
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined
Eg 4:
1) def f1():
2) global a
3) a=10
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)
12) Output
13) 10
14) 10
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
12 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: If global variable and local variable having the same name then we can access
global variable inside a function as follows
Recursive Functions
A function that calls itself is known as Recursive Function.
Eg:
factorial(3)=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1
=6
factorial(n)= n*factorial(n-1)
Eg:
1) def factorial(n):
2) if n==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) return result
7) print("Factorial of 4 is :",factorial(4))
8) print("Factorial of 5 is :",factorial(5))
9)
10) Output
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
13 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
11) Factorial of 4 is : 24
12) Factorial of 5 is : 120
Anonymous Functions:
Sometimes we can declare a function without any name,such type of nameless functions
are called anonymous functions or lambda functions.
The main purpose of anonymous function is just for instant use(i.e for one time usage)
Normal Function:
We can define by using def keyword.
def squareIt(n):
return n*n
lambda Function:
We can define by using lambda keyword
lambda n:n*n
Note: By using Lambda Functions we can write very concise code so that readability of
the program will be improved.
1) s=lambda n:n*n
2) print("The Square of 4 is :",s(4))
3) print("The Square of 5 is :",s(5))
4)
5) Output
6) The Square of 4 is : 16
7) The Square of 5 is : 25
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
14 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3) print("The Sum of 100,200 is:",s(100,200))
4)
5) Output
6) The Sum of 10,20 is: 30
7) The Sum of 100,200 is: 300
Note:
Lambda Function internally returns expression value and we are not required to write
return statement explicitly.
Note: Sometimes we can pass function as argument to another function. In such cases
lambda functions are best choice.
We can use lambda functions very commonly with filter(),map() and reduce() functions,b'z
these functions expect function as argument.
filter() function:
We can use filter() function to filter values from the given sequence based on some
condition.
filter(function,sequence)
Q. Program to filter only even numbers from the list by using filter()
function?
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
15 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) return False
6) l=[0,5,10,15,20,25,30]
7) l1=list(filter(isEven,l))
8) print(l1) #[0,10,20,30]
map() function:
For every element present in the given sequence,apply some functionality and generate
new element with the required modification. For this requirement we should go for
map() function.
Eg: For every element present in the list perform double and generate new list of doubles.
Syntax:
map(function,sequence)
The function can be applied on each element of sequence and generates new sequence.
1) l=[1,2,3,4,5]
2) def doubleIt(x):
3) return 2*x
4) l1=list(map(doubleIt,l))
5) print(l1) #[2, 4, 6, 8, 10]
with lambda
1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
3) print(l1) #[2, 4, 6, 8, 10]
-------------------------------------------------------------
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
16 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 2: To find square of given numbers
1. l=[1,2,3,4,5]
2. l1=list(map(lambda x:x*x,l))
3. print(l1) #[1, 4, 9, 16, 25]
We can apply map() function on multiple lists also.But make sure all list should have same
length.
1. l1=[1,2,3,4]
2. l2=[2,3,4,5]
3. l3=list(map(lambda x,y:x*y,l1,l2))
4. print(l3) #[2, 6, 12, 20]
reduce() function:
reduce() function reduces sequence of elements into a single element by applying the
specified function.
reduce(function,sequence)
reduce() function present in functools module and hence we should write import
statement.
Eg:
Eg:
1) result=reduce(lambda x,y:x*y,l)
2) print(result) #12000000
Eg:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
17 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
In Python every thing is treated as object.
Even functions also internally treated as objects only.
Eg:
1) def f1():
2) print("Hello")
3) print(f1)
4) print(id(f1))
Output
<function f1 at 0x00419618>
4298264
Function Aliasing:
For the existing function we can give another name, which is nothing but function aliasing.
Eg:
1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5) print(id(wish))
6) print(id(greeting))
7)
8) greeting('Durga')
9) wish('Durga')
Output
4429336
4429336
Good Morning: Durga
Good Morning: Durga
Note: In the above example only one function is available but we can call that function by using
either wish name or greeting name.
If we delete one name still we can access that function by using alias name
Eg:
1) def wish(name):
2) print("Good Morning:",name)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
18 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3)
4) greeting=wish
5)
6) greeting('Durga')
7) wish('Durga')
8)
9) del wish
10) #wish('Durga') ==>NameError: name 'wish' is not defined
11) greeting('Pavan')
Output
Good Morning: Durga
Good Morning: Durga
Good Morning: Pavan
Nested Functions:
We can declare a function inside another function, such type of functions are called Nested
functions.
Eg:
1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function calling inner function")
6) inner()
7) outer()
8) #inner() ==>NameError: name 'inner' is not defined
Output
outer function started
outer function calling inner function
inner function execution
In the above example inner() function is local to outer() function and hence it is not possible to call
directly from outside of outer() function.
Eg:
1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
19 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) print("outer function returning inner function")
6) return inner
7) f1=outer()
8) f1()
9) f1()
10) f1()
Output
outer function started
outer function returning inner function
inner function execution
inner function execution
inner function execution
In the first case for the outer() function we are providing another name f1(function aliasing).
But in the second case we calling outer() function,which returns inner function.For that inner
function() we are providing another name f1
Eg: filter(function,sequence)
map(function,sequence)
reduce(function,sequence)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
20 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Function Decorators:
Decorator is a function which can take a function as argument and extend its functionality
and returns modified function with extended functionality.
The main objective of decorator functions is we can extend the functionality of existing
functions without modifies that function.
1) def wish(name):
2) print("Hello",name,"Good Morning")
This function can always print same output for any name
But we want to modify this function to provide different message if name is Sunny.
We can do this without touching wish() function by using decorator.
Eg:
1) def decor(func):
2) def inner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning")
5) else:
6) func(name)
7) return inner
8)
9) @decor
10) def wish(name):
11) print("Hello",name,"Good Morning")
12)
13) wish("Durga")
14) wish("Ravi")
15) wish("Sunny")
16)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
21 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
17) Output
18) Hello Durga Good Morning
19) Hello Ravi Good Morning
20) Hello Sunny Bad Morning
In the above program whenever we call wish() function automatically decor function will
be executed.
1) def decor(func):
2) def inner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning")
5) else:
6) func(name)
7) return inner
8)
9)
10) def wish(name):
11) print("Hello",name,"Good Morning")
12)
13) decorfunction=decor(wish)
14)
15) wish("Durga") #decorator wont be executed
16) wish("Sunny") #decorator wont be executed
17)
18) decorfunction("Durga")#decorator will be executed
19) decorfunction("Sunny")#decorator will be executed
20)
21) Output
22) Hello Durga Good Morning
23) Hello Sunny Good Morning
24) Hello Durga Good Morning
25) Hello Sunny Bad Morning
Eg 2:
1) def smart_division(func):
2) def inner(a,b):
3) print("We are dividing",a,"with",b)
4) if b==0:
5) print("OOPS...cannot divide")
6) return
7) else:
8) return func(a,b)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
22 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
9) return inner
10)
11) @smart_division
12) def division(a,b):
13) return a/b
14)
15) print(division(20,2))
16) print(division(20,0))
17)
18) without decorator we will get Error.In this case output is:
19)
20) 10.0
21) Traceback (most recent call last):
22) File "test.py", line 16, in <module>
23) print(division(20,0))
24) File "test.py", line 13, in division
25) return a/b
26) ZeroDivisionError: division by zero
with decorator we won't get any error. In this case output is:
Decorator Chaining
We can define multiple decorators for the same function and all these decorators will
form Decorator Chaining.
Eg:
@decor1
@decor
def num():
For num() function we are applying 2 decorator functions. First inner decorator will work
and then outer decorator.
Eg:
1) def decor1(func):
2) def inner():
3) x=func()
4) return x*x
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
23 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) return inner
6)
7) def decor(func):
8) def inner():
9) x=func()
10) return 2*x
11) return inner
12)
13) @decor1
14) @decor
15) def num():
16) return 10
17)
18) print(num())
D:\durgaclasses>py decaratordemo1.py
Second Decor(decor1) Execution
First Decor(decor) Function Execution
Hello Durga Good Morning
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
24 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Generators
Generator is a function which is responsible to generate a sequence of values.
We can write generator functions just like ordinary functions, but it uses yield keyword to
return values.
yield
Eg 1:
1) def mygen():
2) yield 'A'
3) yield 'B'
4) yield 'C'
5)
6) g=mygen()
7) print(type(g))
8)
9) print(next(g))
10) print(next(g))
11) print(next(g))
12) print(next(g))
13)
14) Output
15) <class 'generator'>
16) A
17) B
18) C
19) Traceback (most recent call last):
20) File "test.py", line 12, in <module>
21) print(next(g))
22) StopIteration
Eg 2:
1) def countdown(num):
2) print("Start Countdown")
3) while(num>0):
4) yield num
5) num=num-1
6)
7) values=countdown(5)
8) for x in values:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
25 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
9) print(x)
10)
11) Output
12) Start Countdown
13) 5
14) 4
15) 3
16) 2
17) 1
1) def firstn(num):
2) n=1
3) while n<=num:
4) yield n
5) n=n+1
6)
7) values=firstn(5)
8) for x in values:
9) print(x)
10)
11) Output
12) 1
13) 2
14) 3
15) 4
16) 5
Eg: 0,1,1,2,3,5,8,13,21,...
1) def fib():
2) a,b=0,1
3) while True:
4) yield a
5) a,b=b,a+b
6) for f in fib():
7) if f>100:
8) break
9) print(f)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
26 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
10)
11) Output
12) 0
13) 1
14) 1
15) 2
16) 3
17) 5
18) 8
19) 13
20) 21
21) 34
22) 55
23) 89
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
27 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
24) }
25) yield person
26)
27) '''''t1 = time.clock()
28) people = people_list(10000000)
29) t2 = time.clock()'''
30)
31) t1 = time.clock()
32) people = people_generator(10000000)
33) t2 = time.clock()
34)
35) print('Took {}'.format(t2-t1))
Note: In the above program observe the differnce wrt execution time by using list and generators
We will get MemoryError in this case because all these values are required to store in the memory.
Generators:
g=(x*x for x in range(10000000000000000))
print(next(g))
Output: 0
We won't get any MemoryError because the values won't be stored at the beginning
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
28 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com