PythonFunctionChapter
PythonFunctionChapter
CHAPTER-2
FUNCTIONS
For example, to display output, Python has print() function. Similarly, to calculate square
root value, there is sqrt() function and to calculate power value, there is power()
function. Similar to these functions, a programmer can also create his own functions
which are called ‘user-defined' functions. The following are the advantages of functions:
Functions are important in programming because they are used to process data,
make calculations or perform any task which is required in the software
development.
Once a function is written, it can be reused as and when required. So functions are
also called reusable code. Because of this reusability, the programmer can avoid
code redundancy. It means it is possible to avoid writing the same code again and
again.
Functions provide modularity for programming. A module represents a part of the
program. Usually, a programmer divides the main task into smaller sub tasks
called modules. To represent each module, the programmer will develop a
separate function. Then these functions are called from a main program to
accomplish the complete task. Modular programming makes programming easy.
Code maintenance will become easy because of functions. When a new feature has
to be added to the existing software, a new function can be written and integrated
into the software. Similarly, when a particular feature is no more needed by the
user, the corresponding function can be deleted or put into comments.
When there is an error in the software, the corresponding function can be modified
without disturbing the other functions in the software, Thus code debugging
become easy.
The use of functions in a program will reduce the length of the program.
objectname.methodname()
Classname.methodname ()
So, please remember that a function and a method are same except their placement
the way they are called.
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. Consider
the syntax of function, as shown in Figure 9.1:
Here, 'def’ represents the starting of function definition. 'sum' is the name of the function.
After this name, parentheses () are compulsory as they denote that it is a function and
not a variable or something else. In the parentheses, we wrote two variables 'a' and ‘b’.
These variables are called ‘parameters'. A parameter is a variable that receives data from
outside into a function. So, thís 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 body.
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 literal
that is written as the first statement in a module, function or class. Docstrings are
generally written inside triple double quotes or triple single quotes. In our sum()
function, we wrote the following docstring:
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:
c= a + b
print (c)
The parameters 'a' and b' contain the values which are added and the result is stored
into ‘c'. 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:
sum(10, 15)
Here, we are calling the 'sum' function and passing two values 10 and 15 to that 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.
The point is that once a function is written, it can be used again and again whenever:
required. So, functions are called reusable code. Also, observe that integer type da
passed to the function when it is called first time and float type data is passed to
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 siu
the values are passed at the time of calling the function. During run time, 'a' and h' mo
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 avilable
in languages like C or Java.
We can return the result or output from the function using a ‘return' statement in the
body of the function. For example,
When a function does not return any result, we need not write the return statement in
the body of the function. Now, we will rewrite our sum() function such that it will return
the sum value rather than displaying it.
In the above program, the result is returned by the sum() function through 'c' using the
statement:
return c
When we call the function as:
x=sum(10, 15)
the result returned by the function comes into the variable ‘x’. Similarly, when we call the
function as:
y = sum (1.5, 10.75)
The returned result will come into ‘y'.
tested to know whether it is even or odd. If ‘num' is divisible by 2, then we can say it is
even: otherwise it is odd. This logic can be written as:
if num % 2 == 0:
print(num, " is even")
In the preceding statement, the % operator is called modulus operator that gives the
display the remainder of division. If the remainder is 0, then we can display that ‘num’ is
even. This logic is used in even_odd() function in Program 3.
We want to write a function that calculates factorial value of a number. Suppose want to
calculate the factorial of 4, we can write as:
4! = 4X3 X 2 X1
So, if we want to calculate factorial of 'n', then we can write:
n! =n X n-1 X n-2 ... 1
So, the number ‘n' value should be decremented till it reaches the value 1 and the
cumulative products of these numbers should be calculated. We can use a while loop as:
prod = 1 # initialize prod to 1
while n>=1: # repeat as long as n >=1
prod=prod*n # multiply n with prod and store in prod
n=n-1 # decrement n value by 1 every time
This logic is used in creating the fact() function that accepts 'n' as parameter and returns
the ‘prod' value that is nothing but the factorial value of 'n'.
We will write a program that accepts a number and tests whether it is prime or not. We
know a prime number is a number that is not divisible by any other number except by
1 and itself. For example, 5 is a prime number as it is not divisible by another number.
But 1 and 5 divide this number as 1 divides any number and any number divides itself.
So, 1 and 5 need not be counted in deciding the divisibility.
To decide whether 5 is prime or not, we have to divide this number with other numbers
except 1 and 5. It means, we have to divide this number by 2, 3 and 4. If 5 is divisible by
2 or 3 or 4, then we can say it is not prime. If 5 is not divisible by any number from 2 to
4, then we can say it is prime. So, the logic to know whether ‘n' is prime or not is to
divide that number with all numbers from 2 to n-1. If any one number in this range
divides it, then it is not prime, otherwise it is prime. This logic can be written as:
for i in range(2, n):# divide n from 2 to n-1
if n%i == 0: # if divisible by any number it is not prime
When the number is divisible any number in the range from 2 to n-1, it is not prime and
we store 0 into a variable ‘x’. On the other hand, if it is prime, we keep ‘x’ as 1. Thus ‘x’
value indicates whether ‘n' is prime or not. Consider Program 5.
The function prime() that we developed in the previous program can be used to generate
prime number series. Suppose we want to generate the first 10 prime numbers, then the
numbers starting from 2, 3, 4, .. etc. are passed one by one to prime() function. This
function returns 1 if the number is prime; otherwise, the function returns 0. When the
function returns 1, that number is displayed and counted. When the function returns
0, we will not count it as it is not a prime number but we will pass the next number
prime(). When the required number of primes are generated, we will terminate the loop.
In this statement, we are calling the prime() function and passing ’ i' value to it. If ‘i’ is a
prime number, then the function prime() returns 1. So, this if statement looks like this:
if 1:
print(i)
Please understand that python treats 1 as True and 0 as False. Hence the above
statement reads as:
if True:
print(i)
A function returns a single value in the programming languages like C or Java. But in
python a function can return multiple values. When a function calculates multiple results
and wants to return the results, we can use the return statement as:
return a, b, c
Here, three values which are in 'a, 'b’, and 'c’ are returned. These values are returned by
the function as a tuple. Please remember a tuple is like a list that contains a group of
elements. To grab these values, we can use three variables at the time of calling the
function as:
x, y, z = function ()
Here, the variables ‘x’, y' and 'z' are receiving the three values returned by the function.
To understand this practically, we can create a function by the name sum_sub() that
takes 2 values and calculates the results of addition and subtraction. These results are
stored in the variables 'c' and 'd' and returned as a tuple by the function.
def sum_sub (a, b):
c= a+ b
d=a-b
return c, d
Since this function has two parameters, at the time of calling this function, we should
pass two values, as:
x, y = sum_sub(10, 5)
Now, the result of addition which is in ‘c' will be stored into ‘x' and the result of
subtraction which is in 'd' will be stored into ‘y'. This is shown in Program 7.
When several results are returned, we can retrieve them from the tuple using a for loop
or while loop. This is shown in Program 8. This is an extension to Program7.
To understand these points, we will take a few simple programs. In Program 9, we have
taken a function by the name display() that returns a string. This function is called and
the returned string is assigned to a variable ‘x’.
In Program 10, we write message() function inside display() function. We call message()
function from display() and return the result.
In Program 12, we are writing message() function inside display() function. Inside the
display() function, when we write:
return message
This will return the message() function out of display() function. The returned message()
function can be referenced with a new name fun'.
Neither of these two concepts is applicable in Python. In Python, the values are sent to
functions by means of object references. We know everything is considered as an object
in Python. All numbers are objects, strings are objects, and the datatypes like tuples,
lists, and dictionaries are also objects. If we store a value into a variable as:
x = 10
In this case, in other programming languages, a variable with a name ‘x’ is created and
some memory is allocated to the variable. Then the value 10 is stored into the variable
‘x’. We can imagine ‘x' as a box where 10 is stored. This is not the case in Python. In
Python, everything is an object. An object can be imagined as a memory block where we
can store some value. In this case, an object with the value ‘10' is created in memory for
which a name ‘x’ is attached. So, 10 is the object and ’x’ is the name or tag given to that
object. Also, objects are created on heap memory which is a very huge memory that
depends on the RAM of our computer system. Heap memory is available during runtime
of a program.
To know the location of an object in heap, we can use id() function that gives identity
number of an object. For example, consider the following code snippet:
x = 10
id(x)
This number may change from computer to computer as it is computed depending on the
available memory location where object '10' is stored in the computer. In general, two
different objects will have different identity numbers.
When we pass values like numbers, strings, tuples or lists to a function, the references of
these objects are passed to the function. To understand this concept, let's take a small
program. In Program 13, we are calling modify() function and passing ‘x' value, i.e. 10 to
that function. Inside this function, we are modifying the value of ‘x' as 15. Inside the
function, we are displaying ‘x' value and its identity number, as:
print (x, id(x))
In the same manner, after coming out of the function, we are again displaying these
values. Now see the program and its output.
From the output, we can understand that the value of ‘x' in the function is 15 and that is
not available outside the function. When we call the modify) function and pass ‘x’ as:
modify (x)
we should remember that we are passing the object reference to the modify() function.
The object is 10 and its reference name is ‘x’. This is being passed to the modify()
function. Inside the function, we are using:
x = 15
This means another object 15 is created in memory and that object is referenced by the
name ‘x’. The reason why another object is created in the memory is that the integer
objects are immutable (not modifiable). So in the function, when we display ‘x' value
will display 15. Once we come outside the function and display ‘x' value, it will display
the old object value, i.e. 10. Consider the diagram in Figure 9.2. If we display the identity
numbers of ‘x' inside and outside the function, we see different numbers since they are
different objects.
In Python integers, floats, strings and tuples are immutable. That means their data
cannot be modified. When we try to change their value, a new object is created with the
modified value. On the other hand, lists and dictionaries are mutable. That means, when
we change their data, the same object gets modified and new object is not created. In
Program 14, we are passing a list of numbers to modify() function. When we append a
new element to the list, the same list is modified and hence the modified list is available
In Program 14, the list ‘lst' is the name or tag that represents the list object. Before
calling the modify() function, the list contains 4 elements as:
lst = [1,2,3,4]
Please understand that the object here is [1, 2, 3, 4] and its reference name is ‘lst'. When
we call the function as modify(lst), we are passing the object reference ‘lst' to the
function. Inside the function, we are appending a new element ‘9' to the list. Since lists
are mutable, adding a new element to the same object is possible. Hence, append()
method modifies the same object. When we display ‘ lst' inside the function, we can see:
[1, 2, 3, 4, 9]
After coming out of the function, we can see the modified list as the same object got
modified. So, when we display the list outside the function, we can see:
[1, 2, 3, 4, 9]
This is shown in the diagram in Figure 9.3. If we display the identity numbers of the list
inside and outside of the function, we will get same number since they refer to same
object. So, the final point is this: in Python, values are passed to functions by object
references. If the object is immutable, the modified value is not available outside the
function and if the object is mutable, its modified version is available outside the
function.
A caution is needed here. If we create altogether a new object inside the function, then it
will not be available outside the function. To understand this, we will rewrite the
Program.10 where we are passing the following list to the modify() function:
[1, 2, 3, 4]
It means, a new object is created in the function and that is referenced by the name ‘lst’.
So, inside the function, the list is displayed as:
[10, 11, 12]
But the object that is outside the function is different. Hence it remains as it is, ie. [1,
2,3,4]. This can be easily understood from the diagram in Figure 9.4.
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, s2)
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 18
INTRODUCTION TO PYTHON PROGRAMMING Unit III
This function expects two strings that too in that order only. Let's assume that this
function attaches the two strings as s1+s2. So, while calling this function, we are
supposed to pass only two strings as:
attach('New', ‘York')
Suppose, we passed ‘York' first and then ‘New', then the result will be: ‘YorkNew'. Also, if
we 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')
KEYWORD ARGUMENTS
Keyword arguments are arguments that identify the parameters by their names. For
example, the definition of a function that displays grocery item and its price can b e
written as:
def grocery(item, price) :
At the time of calling this function, we have to pass two values and we can mention
which value is for what. For example,
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
which receive these values. We can change the order of the arguments as:
grocery (price=88.00, items=’oil’)
In this way, even though we change the order of the arguments, there will not be any
problem as the parameter names will guide where to store that value. Program 17
demonstrates how to use keyword arguments while calling grocery() function.
DEFAULT ARGUMENTS
We can mention some default value for the function parameters in the definition. Let's
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 second
argument is ‘price' and its default value is mentioned to be 40.00. At the time of calling
this function, if we do not pass 'price' value, then the default value of 40.00 is taken. If
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.
Sometimes, the programmer does not know how many values a function may receive,
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 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.
A keyword variable length argument is an argument that can accept any number of
values provided in the format of keys and values. If we want to use a keyword variable
length argument, we can declare it with** before the argument as:
def display (farg, **kwargs):
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:
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.
when the programmer wants to use the global variable inside a function, he can use the
keyword ‘global’ before the variable in the beginning of the function body as:
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 23
INTRODUCTION TO PYTHON PROGRAMMING Unit III
global a
In this way, the global variable is made available to the function and the programmer
can work with it as he wishes. In the following program, we are showing how to work
with a global variable inside a function.
When the global variable name and local variable names are same, the programmer will
face difficulty to differentiate between them inside a function. For example there is a
global variable ‘a' with some value declared above the function The programmer is
writing a local variable with the same name ‘a' with some other value inside the function
Consider the following code
a=1 #this is global var
def myfunction():
a= 2 #a is local var
Now, if the programmer wants to work with global variable, how is it possible? If he uses
‘global’ keyword, then he can access only global variable and the local variable is no
more available.
The globals() function will solve this problem. This is a built in function which returns a
table of current global variables in the form of a dictionary. Hence, using this function
we can refer to the global variable 'a', as: globals()['a'] Now, this value can be assigned to
another variable, say x' and the programmer can work with that value. This is show in
Program 23.
The input() function takes a group of integers as a string. This string is split into pieces
where a space is found as a space is the default for split() method. These pieces are then
converted into integers by the int() function and returned into the list ‘lst': We pass this
list of integers to the calculate() function as:
x, y= calculate(lst)
The calculate() function returns sum and average which are stored into x and y
respectively.
Program 25 shows how to accept a group of strings from keyboard and display them
using display() function
RECURSIVE FUNCTIONS
A function that calls itself is known as ‘recursive function'. For example, we can write the
factorial of 3 as:
Now, if we know that the factorial(0) value is 1, all the preceding statements will
evaluate and give the result as:
From the above statements, we can write the formula to calculate factorial of any
number ‘n’ as:
factorial (n) = n * factorial (n-1)
When we observe this formula, we can understand that the factorial() function to
calculate factorial of ‘n' value will call itself to calculate factorial of ‘n-1' value. So, we can
implement factorial() function using recursion, as shown in Program 26.
Let's write a program to solve the Towers of Hanoi problem through recursion. Towers
of Hanoi is a famous game from ancient China. It is believed that this game helps to
develop the intelligence of the children who play it. In this game, there will be a group of
disks on a pole 'A' such that the biggest disk will be at the bottom and the smaller disks
will be on its top. One is supposed to transfer all these disks from pole 'A’ to another
pole. Let's say ‘C’ in minimum number of steps. While moving these disks from 'A' to 'C’,
we can take the help of an intermediate pole ‘B'. But, the rule is that while moving the
disks from one pole to another, we should never place a bigger disk on a smaller disk.
For example, to transfer 3 disks from the pole ‘A' to 'C' with the help of an intermediate
pole ‘B’. we can use the steps shown in Figure 9.5:
These steps can be performed easily by using recursion. Suppose the number of disks to
be moved is ‘n'. If n==1, move that disk from ‘A' to 'C'. Otherwise, the process of moving
‘n' disks will be divided into two parts: move the top n-1 disks and move the remaining 1
disk. The steps are:
1. Move top n-1 disks from 'A' to B', using ‘C' as intermediate pole.
2. Move remaining disks, i.e. 1 disk from 'A' to ‘C’.
3. Move n-1 disks from ‘B' to ‘C' using ‘A' as intermediate pole.
This logic is presented in Program 27. This program contains towers() function which
calls itself and is defined as:
def towers (n, a, c, b):
Here ‘n' represents the number of disks to move. The variables a, c, b indicate that the
disks need to be moved from pole 'A' to pole ‘C' by taking the help of intermediate
pole B.
The concept of recursion helps the programmers to solve complex programs in less
number of steps. Imagine if we attempt to write the Towers of Hanoi program without
using recursion, it would have been a highly difficult task.
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
is:
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
as:
f = lambda x: x*x
Here, ‘f’ is the function name to which the lambda expression is assigned. Now, if we call
the function f() as:
value = f(5)
Now, ‘value' contains the square value of 5, i.e. 25. This is shown in Program 28.
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.
The following is a program that contains a lambda function to find the bigger number
two given numbers.
Now, is_even() function acts on every element of the list ‘lst' and returns only those
elements which are even. The resultant element can be stored into another list. This is
shown in Program 31.
Passing lambda function to filter() function is more elegant. We will rewrite the program
31 using lambda function.
When the same program is rewritten using lambda function, it becomes more elegant.
This is done in Program 34.
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, lst1, lst2)
Here, lambda function has two arguments ‘x' and y'. Hence, ‘x' represents ‘lst1' and ‘y’
represents ‘lst2’. Since lambda is showing x*y, the respective elements from lst1 and lst2
are multiplied and the product is returned.
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. A
decorator takes the result of a function, modifies the result and returns it. Thus
decorators are useful to perform some additional processing required by a function.
Decorators concept is a bit confusing but not difficult to understand. The following steps
are generally involved in creation of decorators:
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 décor() 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 (i.e. 10) is
incremented by 2 by the decor() function. Consider Program 37.
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 décor() 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 num()
function. When we apply the decorator in this way, we need not call the decorator
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
function is called. The same program revised version using the ‘@' symbol is shown in
Program 38.
We will extend this program where we are going to add one more decorator by the name
'decor1()' 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.
To apply the decorators to num() function using ‘@' symbol, we can rewrite the above
program as Program 40,
GENERATORS
Generators are functions that return a sequence of values. A generator function is
written like an ordinary function but it uses ‘yield' statement. This statement is useful to
return the value. For example, let's write a generator function to return numbers from x
to y
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 w e call this function by passing 5 and 10 as:
g=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 of
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 numbers
from x to y and displaying those numbers.
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 ‘lst' we can using list() function as:
lst = list (g)
Now, the list ‘lst' contains the elements: (5, 6, 7, 8, 9, 10].
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 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, 'C' using yield statements. So, yield statement returns
the elements from a generator function into a generator object. So, when we call mygen0
function as:
g=mygen()
The characters ‘A’,’B’,’C' are contained in the generator object ‘g'. Using next(g) we can
STRUCTURED PROGRAMMING
The purpose of programming is to solve problems related to various areas. Starting from
simple problems like adding two numbers to very complex problems like designing the
engine of an aircraft, any problem can be solved through programming. When there is a
simple problem, the programmer can solve it by writing a simple program. But when
there is a complex problem, he may have to develop a lengthy code.
Solving a complex problem is a challenging task for the programmer. For this purpose
structured programming is the strategy used by programmers in general. In structured
programming, the main task is divided into several parts called sub tasks and each of
these sub tasks is represented by one or more functions. By using these functions, the
programmer can accomplish the main task. To understand this concept, let's take an
example where we are supposed to calculate the net salary of an employee. Every
employee will have some basic salary. The company may provide some benefits like
dearness allowance (da) and house rent allowance (hra), which when added to basic
salary will give the gross salary. So,
Gross salary = basic salary + da + hra.
The net salary or take home salary is calculated based on gross salary. After making
deductions like provident fund and income tax from the gross salary, the remaining
amount is called net salary. So,
Net salary = gross salary - pf - income tax.
Hence, in a program to calculate the net salary, we need to calculate the following: da
hra, pf and income tax. All these will come under sub tasks and to represent these sub
tasks, we can write functions. Finally, using these functions we can calculate the net
salary of the employee. This methodology is called structured programming or
sometimes functional programming. Consider the diagram given in Figure 9.7:
We are going to calculate the net salary of an employee by developing the functions: da(),
hra(), pf() and itax(). Once these functions are developed, then calculating gross salary
and net salary will employee. become very easy. Consider Program 43: Creating our Own
Modules in Python
A module represents a group of classes, methods, functions and variables. While we are
developing software, there may be several classes, methods and functions. We should
first group them depending on their relationship into various modules and later use
these modules in the other programs. It means, when a module is developed, it can be
reused in any program that needs that module.
In Python, we have several built-in modules like sys, io, time etc. Just like these
modules, we can also create our own modules and use then whenever we need them.
Once a module is created, any programmer in the project team can use that module
Hence, modules will make software development easy and faster.
Now, we will create our own module by the name 'employee' and store the functions
da(),hra(),pf() and itax() in that module. Please remember we can also store classes an
variables etc. in the same manner in any module. So, please type the following functions
and save the file as 'employee.py'.
Now, we have our own module by the name 'employee.py'. This module contains 4
functions which can be used in any program by importing this module. To import the
module, we can write:
import employee
In this case, we have to refer to the functions by adding the module name as:
employee.da(), employee.hra(), employee.pf( ), employee.itax(). This is a bit
cumbersome and hence we can use another type of import statement as:
from employee import *
In this case, all the functions of the employee module is referenced and hence, we can
refer to them without using the module name, simply as: da(), hra(), pf() and itax(). Now
see the following program, where we are using the 'employee' module and calculating
the gross and net salaries of an employee.
Let's assume that we have written a program. When this program is run, Python
interpreter stores the value ‘__main__’ into the special variable ‘__name__’. Hence, we can
check if this program is run directly as a program or not as:
if __name__ == ‘__main__’ :
print( This code is run as a program')
Suppose, if ‘__name__’ variable does not contain the value’_ _main__’, it represents that
this code is run as a module from another external program. To understand this concept,
irst we will write a program with a display() function that displays some message as
‘Hello Python!'. This code is shown in Program 45.
So, the code in the Program 45 is run directly by the Python interpreter and hence it is
saying that ‘this code is run as a program'.
Now, we will write another program (Program 46) where we want to import ‘one.py’
program as a module and call the display() function.
In Program 46, when the first statement: ‘import one' is executed by the Python
interpreter, it will set the value of the special variable __name__ as 'one' (i.e. the module
name) in one.py program and hence we got the output as: ‘This code is run as a module'