iiiBCA AY2021-22 5thsem
FUNCTIONS IN PYTHON
Difference between a Function and a Method
We discussed that a function contains a group of statements and performs task. A function can be
written individually in a Python program A function using its name When a function is written inside a
class, it becomes a method is called using one of the following ways
objectname .methodname()
classname .methodname()
So, please remember that a function and a method are same except the way they are called. In this
chapter, we will learn how to create and use our own functions Creating a function means defining a
function or writing a function. Once a function is defined, it can be used by calling the function
Defining a Function
We can define a function using the keyword def followed by function name. After the function name,
we should write parentheses () which may contain parameters C the syntax of function.
For example, we can write a function to add two values as.
def sum (a, b):
Here, 'def represents the starting of function definition. 'sum' is the name of the func After this name,
parentheses () are compulsory as they denote that it is a function not a variable or something else In
the parentheses, we wrote two variables 'a' and These variables are called 'parameters' A parameter
is a variable that receives data b outside into a function. So, this function can receive two values from
outside and those values are stored in the variables 'a' and 'b'
After parentheses, we put a colon () that represents the beginning of the function The function body
contains a group of statements called 'suite' Generally, we should write a string as the first statement
in the function body. This string is called a docstring that gives information about the function. Please
remember a docstring is a string that is written as the first statement in a module, function or class.
Docstring generally written inside triple double quotes or triple single quotes. In our sum () function
we wrote the following docstring
“”” This function finds sum of two numbers “””
This docstring contains only one line but we can write docstrings spanning several lines However these
docstrings are optional That means it is not compulsory to write them When an API (Application
Programming Interface) documentation file is created, the function name and docstring are stored in
that file thus providing clear description about the function Writing docstrings is a good programming
habit. After writing the docstring in the function, the next step is to write other statements which
constitute the logic of the function This reflects how to do the task These statements should be written
using proper indentation In our example, we want to find the sum of two numbers Hence, the logic
would be
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
c=a+b
print (c)
The parameters 'a' and b' contain the values which are added and the result is stored into Then the
result is displayed using the print () function So. this function can accept two values and display their
sum
Calling a Function
A function cannot run on its own. It runs only when we call it So, the next step is to call the function
using its name While calling the function, we should pass the necessary values to the function in the
parentheses as Here, we are calling the 'sum' function and passing two values 10 and 15 to that
sum (10, 15)
function When this statement is executed, the Python interpreter jumps to the function definition and
copies the values 10 and 15 into the parameters 'a' and b' respectively. These values are processed in
the function body and result is obtained. The values passed to a function are called 'arguments' So, 10
and 15 are arguments. In Program 1. we are showing the sum () function discussed so far
Program 1: A function that accepts two values and finds their sum
# a function to add two numbers.
def sum (a, b): “ “ “This function finds sum of two numbers” “ “
c = a+b
print ('Sum=', c)
#call the function
sum (10, 15)
sum (1.5, 10.75) # call second time.
Output
C:\>python [Link]
Sum=25
Sum=12.25
In Program 1, we are calling the sum () function two times as:
sum (10, 15) # call first time and pass 10 and 15
sum (1. 5. 10.75) # call second time and pass 1.5 and 10.75
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
The point is that once a function is written, it can be used again and again when required So, functions
are called code Also, observe that integer type data passed to the function when it is called first time
and float type data is passed to t same function when called second time Observe the sum () function
definition def sum (a, b):
The parameters 'a' and b' do not know which type of values they are going to receive the values are
passed at the time of calling the function. During run time, 'a' and ‘b’ may assume any type of data,
may be int or may be float or may be strings. This is called 'dynamic typing' In dynamic typing, the type
of data is determined only during runtime not at compile time Dynamic typing is one of the features
of Python that is not available in languages like C or Java.
Returning Results from a Function
We can return the result or output from the function using a 'return' statement in the body of the
function. For example,
return c # returns c value out of function
return 100 # returns 100
return lst # return the list that contains values
return x, y, c # returns 3 values
When a function does not return any result, we need not write the return statement is the body of
the function. Now, we will rewrite our sum () function such that it will return the sum value rather
than displaying it. This is done in Program 2.
Program
Program 2: A Python program to find the sum of two numbers and return the result from the function
#a function to add two numbers
def sum (a, b);
“”” This function finds sum of two numbers “””
c=a+b
return c #return result
# Call the function.
X = sum (10, 15)
print ('The sum is: ‘, x)
y =sum (1.5, 10.75)
print ('The sum is:’,y)
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
Output:
C:\>python [Link]
The sum 15: 25
The sum is: 12.25
Formal and Actual Arguments
When a function is defined, it may have some parameters These parameters are receive values from
outside of the function They are called 'formal argumenta call the function, we should pass data or
values to the function. These values actual arguments In the following code, 'a' and 'b' are formal
arguments and are actual arguments
def sum (a, b): #a, b are formal arguments
c = a+b
print(c)
# Call the function
x=10; y=15
Sum (x, y) # x, y are actual arguments
The actual arguments used in a function call are of 4 types
• Positional arguments
• Keyword arguments
• Default arguments
• Variable length arguments
Positional Arguments
These are the arguments passed to a function in correct positional order Here, the number of
arguments and their positions in the function definition should match exactly with the number and
position of the argument in the function call. For example, take a function definition with two
arguments as
def attach (s1, 52)
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
This function expects two strings that too in that order only Let's assume that this function attaches
the two strings as sl+82 So, while calling this function, we are supposed to pass only two strings as
attach('New', 'York')
The preceding statement displays the following output.
New York
Suppose, we passed 'York' first and then 'New', then the result will be "York New” Also, if se try to
pass more than or less than 2 strings, there will be an error. For example, if we call the function by
passing 3 strings as:
attach ('New’, York', ‘City')
Then there will be an error displayed.
Program 16: A Python program to understand the positional arguments of a function.
#Positional arguments demo
def attach (s1, 52):
“””to join s1 and s2 and display total string”””
s3= s1+s2
print ('Total string: +53)
# Call attach () and pass 2 strings
attach ('New', 'York') # positional arguments
Output
C:\>python [Link]
Total string: NewYork
Keyword Arguments
Keyword arguments are arguments that identify the parameters by their names example the
definition of a function that displays grocery item and its price written as
def grocery (item, price):
At the time of calling this function, we have to pass two values and we can m. For example, which
value is for what
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
grocery (item="Sugar”, price-50.75)
Here we are mentioning a keyword 'item' and its value and then another keyword price and its value
Please observe these keywords are nothing but the parameter names
receive these values We can change the order of the arguments as
grocery (price-88.00, item='oil')
In this way, even though we change the order of the arguments, there will not be problem as the
parameter names will guide where to store that value Program demonstrates how to use keyword
arguments while calling grocery () function.
Program
Program 17: A Python program to understand the keyword arguments
#key word arguments demo
def grocery (item, price):
“ “ “ to display the given arguments “ “ “
print('Item= %s’ % item)
print('Price = %.2f' % price)
#call grocery and pass 2 arguments
grocery (item=’ Sugar', price=50.75)
grocery (price=88.00, item='oil') # keyword arguments
Output
C\>python [Link]
Item= Sugar
Price = 50 75
Item = oil
Price = 88.00
Default Arguments
We can mention some default value for the function parameters in the definition. Le take the
definition of grocery () function as:
def grocery (item, price=40.00):
Here, the first argument is 'item' whose default value is not mentioned But the se argument 'price'
and its default value is mentioned to be 40.00 At the time of calling this function, if we do not pass
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
'price' value, then the default value of 40,00 is taken we mention the 'price' value, then that
mentioned value is utilized So, a default argument is an argument that assumes a default value if a
value is not provided in the function call for that argument Program 18 will clarify this.
Program 18: A Python program to understand the use of default arguments in a default arguments
demo
def grocery (item. Price=40.00) :
“ “ “ to display the given arguments “ “ “
print (‘Item =%s’%item)
print ("Price=%.2F” % price) #call grocery and pass arguments
grocery(item=’ Sugar’, price=50.75)
grocery (item="Sugar”) # default value for price is used
Output
C:>python [Link]
Item= Sugar
Price = 50.75
Item= Sugar
Price = 40.00
Variable Length Arguments
Sometimes, the programmer does not know how many values a function may receive. In that case,
the programmer cannot decide how many arguments to be given in the function definition. For
example, if the programmer is writing a function to add two numbers, he can write
add (a, b)
But the user who is using this function may want to use this function to find sum of three numbers. In
that case, there is a chance that the user may provide 3 arguments to this function as
add (10, 15, 20)
Then the add () function will fail and error will be displayed If the programmer wants to develop a
function that can accept 'n' arguments, that is also possible in Python For this purpose, a variable
length argument is used in the function definition. A variable length argument is an argument that can
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
accept any number of values The variable length argument is written with a symbol before it in the
function definition as def add (farg, *args):
Here, ‘farg' is the formal argument and "args' represents variable length argument. We can pass 1 or
more values to this "args” and it will store them all in a tuple A tuple is like a list where a group of
elements can be stored In Program 19, we are showing how to use variable length argument.
Program
Program 19: A Python program to show variable length argument and its use #args can take 0 or more
values variable length argument demo args):
to add given number, farg)
def add (farg, *args):
print ('Formal argument=’, farg)
sum=0
for i in args:
sum+=i
print ('Sum of all numbers= ', (farg+sum))
# Call add () and pass arguments
add (5, 10)
add (5, 10, 20, 30)
Output
C:\>python [Link]
Formal argument= 5
Sum of all numbers= 15
Formal argument= 5
Sum of all numbers= 65
Local and Global Variables
When we declare a variable inside a function, it becomes a local variable. A local variable is a variable
whose scope is limited only to that function where it is created. That means the local variable value is
available only in that function and not outside of that function. In the following example, the variable
'a' is declared inside my function () and hence it is available inside that function. Once we come out of
the function, the variable 'a' is removed from memory and it is not available. Consider the following
code:
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
#Local variable in a function def my function ():
a=1 #this is local var
a+=1 #increment it #displays 2
print (a)
my function ()
print (a)# error, not available
See the last statement where we are displaying 'a’ value outside the function. This statement raises
an error with a message: name 'a' is not defined. When a variable is declared above a function, it
becomes global variable. Such variables are available to all the functions which are written after it.
Consider the following code
#Global variable example
a=1 # this is global var
def myfunction ():
b=2 #this is local var
print('a=', a) #display globalvar
print('b= ‘,b) #display Tocalvar
myfunction ()
print(a) #available
print (b) # error, not available
Whereas the scope of the local variable is limited only to the function where it is declared, the scope
of the global variable is the entire program body written below it.
The Global Keyword
Sometimes, the global variable and the local variable may have the same name in that case, the
function, by default, refers to the local variable and ignores the global variable So, the global variable
is not accessible inside the function but outside of it, it is accessible. Consider Program 21.
Program
Program 21: A Python program to understand global and local variables
#Same name for global and local variables
a-1 #this is global var
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
def myfunction():
a=2 #this is local var
print ('a=', a) #display local var
my function ()
print ('a=’, a) #display global var
Output
C:\>python [Link]
a=2
a= 1
When the programmer wants to use the global variable inside a function, he can use keyword global'
before the variable in the beginning of the function body as
global a
Anonymous Functions or Lambdas
A function without a name is called 'anonymous function' So far, the functions we w were defined
using the keyword 'def. But anonymous functions are not defined using ‘def’. They are defined using
the keyword lambda and hence they are also called Lambda functions
Let's take a normal function that returns square of a given value
def square(x):
return xx
The same function can be written as anonymous function as
lambda x:x*x Observe the keyword lambda’. This represents that an anonymous function is being
created. After that, we have written an argument of the function, i.e., 'x' Then colon represents the
beginning of the function that contains an expression x * x. Please observe that we did not use any
name for the function here. So, the format of lambda functions
lambda argument _list: expression
Normally, if a function returns some value, we assign that value to a variable as
y = square (5)
But lambda functions return a function and hence they should be assigned to a function
f = lambda x: x*x
value = f (5)
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
Now, 'value' contains the square value of 5, i.e., 25. This is shown in Program 28.
Program
Program 28: A Python program to create a lambda function that returns a square value
of a given number
#a lambda function to calculate square value
f =lambda x: x*x #write lambda function
value = f (5) # call lambda function
print ('Square of 5’, value) #display result
Output:
C:\>python fun. Square of 5= 25
Lambda functions contain only one expression and they return the result implicitly. Hence, we should
not write any 'return' statement in the lambda functions. Here is a lambda function that calculates
sum of two numbers.
Program 29: A lambda function to calculate the sum of two numbers.
#a lambda function
f=lambda x, y: x+y
Result=f (1.55, 10)
print ('Sum=’, result) #call lambda function #display result
Output
C:\>python [Link]
Sum =11.55
The following is a program that contains a lambda function to find the bigger number in wo given
numbers.
Program 30: A lambda function to find the bigger number
#a lambda function that returns bigger number in two given numbers.
max= lambda x, y: x if x>y else y # write lambda function
a, b = [int(n) for n in input ("Enter two numbers: "). split (',')]
print ('Bigger number = ', max (a, b))
Output
C:\>python [Link] Enter two numbers: 10, 25
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
Bigger number = 25
Because a lambda function is always represented by a function, we can pass a lambda function to
another function. It means we are passing a function (i.e., lambda) to another function. This makes
processing the data very easy. For example, lambda functions are generally used with functions like
filter (), map) or reduce ().
Using Lambdas with filter () Function
The filter function is useful to filter out the elements of a sequence depending on the result of a
function. We should supply a function and a sequence to the filter () function
filter (function, sequence)
Here, the function represents a function name that may return either True or False; and ‘sequence'
represents a list, string or tuple. The’ function' is applied to every element of the’ sequence' and when
the function returns True, the element is extracted otherwise it ignored. Before using the filter ()
function, let's first write a function that tests whether a given number is even or odd.
def is_even(x):
if x%2=0:
return True
else:
return False
# call lambda function
Now, we can use this function inside filter) to test the elements of a list 1st as filter (is_even, 1st) Now,
is even () function acts on every element of the list 1st' and returns only elements which are even. The
resultant element can be stored into another list.
Program:
Program 31: A Python program using filter () to filter out even numbers from a list
filter () function that returns even numbers from a list
def is_even(x)
if x%2=0:
return True
else:
return false
#Let us take a list of numbers
1st = [10, 23. 45, 46, 70, 99]
#call filter () with is even() and 1st
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
1st1= list (filter (is_even, 1st))
print (1st1)
Output
C:\>python [Link]
[10, 46, 70]
Passing lambda function to filter () function is more elegant. We 31 using lambda function.
Program
Program 32: A lambda that returns even numbers from a list.
# a lambda function that returns even numbers from a list
1st = [10, 23, 45, 46, 70, 99]
1st1= list (filter (lambda x: (x%2= 0), 1st))
print(1st1)
Using Lambdas with map () Function
The map function is similar to filter () function but it acts on each element of the sequence and perhaps
changes the elements. The format of map () function is:
map (function, sequence)
The function' performs a specified operation on all the elements of the sequence and the modified
elements are returned which can be stored in another sequence In Program 33 we are using map ()
function to find squares of elements of a list.
Program
Program 33: A Python program to find squares of elements in a list. # map () function that gives squares
def squares (x):
return x*x #take a list of numbers
1st= [1, 2, 3, 4, 5] # call map () with squares and 1st
1st1= list (map (squares, 1st))
print (1st1)
Output:
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
C:\>python [Link]
[1, 4, 9, 16, 25]
When the same program is rewritten using lambda function, it becomes more elegant. This is done in
Program 34.
Program 34: A lambda function that returns squares of elements in a list.
#Lambda that returns squares
1st = [1, 2, 3, 4, 5]
1stl=list (map (lambda x: x*x, lst))
print (lst1)
It is possible to use map () function on more than one list if the lists are of same length. In this case,
map () function takes the lists as arguments of the lambda function and does the operation. For
example,
map (lambda x, y: x*y, 1stl, 1st2)
Here, lambda function has two arguments 'x' and 'y'. Hence, x' represents 1st!' and 'y' represents 1st2'.
Since lambda is showing x*y, the respective elements from Ist1 and 1st2 are multiplied and the
product is returned.
Program 35: A Python program to find the products of elements of two different lists using lambda
function.
#Lambda that returns products of elements of two lists
lst1= [1, 2, 3, 4, 5]
lst2= [10, 20, 30, 40, 50]
lst3=list (map (lambda x, y: x*y, 1st1, 1st2))
print (1st3)
Output:
C:\>python [Link]
[10, 40, 90, 160, 250]
Using Lambdas with reduce () Function
The reduce () function reduces a sequence of elements to a single value by processing the elements
according to a function supplied. The reduce () function is uses in the format: reduce (function,
sequence)
For example, we write the reduce) function with a lambda expression, an reduce lambda ³, 4, 5 take a
list of numbers
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
reduce (lambda x,y:x*y,lst) Here, the reduce() function reduces the list to a final value as indicated by
the las function The lambda function is taking two arguments and returning their t Hence, starting
from the 0th element of the list 1st, the first two elements are mu and the product is obtained Then
this product is multiplied with the third element and the product is obtained Again this product is
multiplied with the fourth element and on
Program
Program 36: A lambda function to calculate products of elements of a list #Lambda that returns
products of elements of a list
from functools import *
lst = [1, 2, 3, 4, 5]
result = reduce (lambda x, y: x*y, 1st):
print (result)
Output
C:\>python [Link]
120
Since reduce () function belongs to functools module in Python, we are importing all from that module
using the following statement in Program 36.
from functools import*
As another example, to calculate the sum of numbers from 1 to 50 we can write reduce () function
with a lambda function, as:
sum reduce (lambda a, b: a+b, range (1,51))
print (sum)
1275
Function Decorators
A decorator is a function that accepts a function as parameter and returns a function decorator takes
the result of a function, modifies the result and returns it Thus decorators are useful to perform some
additional processing required Decorator’s concept is a bit confusing but not difficult to understand.
The following steps are generally involved in creation of decorators: 1. We should define a decorator
function with another function name as parameter as by a function.
An example, let's define a decorator function decor) with fun' as parameter. def decor (fun): 2. We
should define a function inside the decorator function. This function actually modifies or decorates
the value of the function passed to the decorator function. As an example, let's write inner () function
in the decor () function. Our assumption is that
this inner () function increases the value returned by the function by 2.
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
def decor (fun):
def inner ():
value= fun ()
return value+2 # return inner # access value returned by fun () #increase the value by 2 #
return the inner function
In the previous code, observe the body of the inner () function. We have accessed the value' returned
by the function 'fun', and added 2 to it and then returned it. 3. Return the inner function that has
processed or decorated the value. In our example, in the last statement, we were returning inner ()
function using return statement. With this, the decorator is completed. The next question is how to
use the decorator. Once a decorator is created, it can be used for any function to decorate or process
its result. For example, let's take num () function that returns some value, e.g., 10.
def num ():
return 10
Now, we should call decor () function by passing num () function name as:
Result_fun =decor (num)
Now the name 'num' is copied into the parameter of the decor () function. Thus, fun" refers to 'num'.
In the inner () function, 'value' represents 10 and it is incremented by 2. The returned function inner'
is referenced by 'result fun'. So, result fun' indicates the resultant function. Call this function and print
the result as:
print (result_ fun ())
This will display 12. Thus, the value returned by the num () function (ie. 10) is incremented by 2 by the
decor () function. Consider Program 37.
Program 37: A decorator to increase the value of a function by 2. a decorator that increments the
value of a function by 2
def decor (fun): # this is decorator function # this is the inner function that modifies
def inner ():
value = fun ()
return value+2
return inner # return inner function
#Take a function to which decorator should be applied
def num ():
return 10
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
#call decorator function and pass num result fun decor(num) #result fun represents 'inner' function
print (result _fun ()) # call result fun and display the result
Output
C:\>python [Link]
To apply the decorator to any function, we can use the @symbol and decorator name just above the
function definition. For example, to apply our decor () function to the num function, we can write
@decor statement above the function definition as:
@decor #apply decorator decor to the following function
def num ():
return 10
It means decor () function is applied to process or decorate the result of the ni function when we apply
the decorator in this way, we need not call the decorate explicitly and pass the function name. Instead,
we can call our num () function naturally as
print (num ())
So, the symbol is useful to call the associated decorator internally, whenever the function is called the
same program revised version using the @symbol is shown in Program 38
Program:
Program 38: A Python program to apply a decorator to a function using @ symbol.
#a decorator that increments the value of a function by 2
def decor (fun): # this is decorator function
def inner () #this is the inner function that modifies
value = fun () return value+2
return inner #return inner function
#Take a function to which decorator should be applied.
@decor
def num (): #apply decor to the below function
return 10
#Call num () function and display its result
print (num ())
Output
C:\>python [Link]
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
12
We will extend this program where we are going to add one more decorator by the name decor10'
that doubles the value of the function passed to it. That means we want to apply two decorators to
the same function num () to decorate its result Consider
Program 39: A Python program to create two decorators
# a decorator that increments the value of a function by 2
def decor (fun):
def inner():
value= fun()
return value+2
return inner
#a decorator that doubles the value of a function
def decor1(fun):
def inner ():
value = fun ()
return value *2
return inner
#take a function to which decorator should be applied
def num ():
return 10
#callnum() function and apply decorl and then decor result fun decor (decor1(num)) print (result fun())
Output
python [Link]
22
To apply the decorators to num) function using @ symbol, we can rewrite the above program as
Program 40
Program 40: A Python program to apply two decorators to the same function using @symbol.
#a decorator that increments the value of a function by 2
def decor (fun):
def inner ():
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
value = fun ()
return value+2
return inner
# a decorator that doubles the value of a function
def decor1(fun):
def inner ():
value = fun ()
return value 2
return inner
# take a function to which decorator should be applied
@decor
@decor1
def num ():
return 10
#call num() function and apply decor1 and then decor print (num())
Output
C-python [Link]
So, the syntax of decorators is
@dec1
@dec2
def func (arg1, arg2,..):
pass
This is equivalent to
def func (argi, arg2, ...):
pass
func= dec1(dec2(func))
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
Generators
Generators are functions that return a sequence of values. A generator function is like an ordinary
function but it uses yield' statement This statement is useful to the value For example, let's write a
generator function to return numbers from 2
def mygen (x, y): #our generator name is 'mygen'
while x<=y: # this is the loop repeats from x to y
yield x # return x value
X+=1 # increment x value by 1
When we call this function by passing 5 and 10 as
9= mygen (5, 10)
Then the mygen () function returns a generator object that contains sequence of numbers as returned
by yield' statement So, 'g' refers to the generator object with the sequence numbers from 5 to 10 We
can display the numbers from 'g' using a for loop as
for i in g:
print (i, end=' ')
In the following program, we are creating a generator function that generates from x to y and
displaying those numbers.
Program
Program 41: A Python program to create a generator that returns from x to y
#generator that returns sequence from x to y
def mygen (x, y):
while x<=y:
yield x
X+=1
#fill generator object with 5 and 10
g=mygen (5, 10) # display all numbers in the generator
for I in g:
print (1, end=’ ‘)
Output
C:\>python [Link] 5 6 7 8 9 10
Once the generator object is created, we can store the elements of the generator into a list and use
the list as we want For example, to store the numbers of generator 'g' into a list 1st we can using list()
function as
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
1st = list (g)
Now the list 1st' contains the elements (5, 6, 7, 8, 9, 101.
if we want to retrieve element by element from a generator object, we can use next () function as
print (next (g))
will display first element in 'g' When we call the above function the next time, it will display the second
element in 'g' Thus by repeatedly calling the next () function, we will be able to display all the elements
of ‘g’. In the following program, a simple generator is created that returns ‘A’, 'B', 'c'.
def mygen ():
yield ‘A’:
yield ‘B’:
yield ‘C’:
Here mygen () is returning 'A', 'B', ^ prime C^ prime using yield statements So, yield statement returns
the elements from a generator function into a generator object So, when we call mygen () function as
g = mygen ()
The characters ‘A’,’B’,’C’ are contained in the generator object 'g Using next(g) we can refer to these
elements Consider Program 42.
Program
Program 42: A generator that returns characters from A to C
#Generator that returns characters from A to C
def mygen ()
yield ‘A’:
yield ‘B’:
yield ‘C’:
#Call generator function and get generator object g
g = mygen () #display all characters in the generator
print (next (g))
print (next (g))
print (next (g))
print (next (g)) #error
Vijetha Bhat,Canara College
iiiBCA AY2021-22 5thsem
Traceback (most recent call last):
File "[Link]", line 14, in <module>
print (next (g)) #error
Stop Iteration
Vijetha Bhat,Canara College