Python Modules
INTRODUCTION
Dinesh Nagambaram (not for sales)
As our programs become bigger and more complex,
Dinesh Nagambaram (not for sales)
the need to organize our code becomes greater. A
large and complex program should be divided into
files/functions that perform specific tasks. As we
Dinesh Nagambaram (not for sales)
write more and more functions in a program, we
should consider organizing them by storing them in
modules.
Dinesh Nagambaram (not for sales)
A module is simply a file that contains a Python
code. When we break a program into modules, each
Dinesh Nagambaram (not for sales)
module should contain functions that perform
related tasks. For example, suppose we are writing
an accounting system. We would store all the
Dinesh Nagambaram (not for sales)
account receivable functions in their own module
and the account payable functions and all the STANDARD BUILT-IN PYTHON MODULES
Dinesh Nagambaram (not for sales)
payroll functions in their respective modules. This
approach, called modularization, makes a program
easier to understand, test and maintain.
In Python, we have worked with script mode so far,
which provides the capability to retain our work for
future usage. For working in script mode, we need
Dinesh Nagambaram (not for sales)
Even tiny real-world applications contain thousands
of lines of code. In fact, applications that contain
to write a module/function Python and save it in the
file having .py extension. A Python module is written
Dinesh Nagambaram (not for sales)
millions of lines of code are somewhat common.
Imagine trying to work with a file large enough to
once and used/called as many times as required.
Modules can be categorized into the following two
contain millions of lines of code-you would never
types:
Dinesh Nagambaram (not for sales)
find anything so easily. In short, we need some
method to organize the code into smaller pieces that (i) Built-in Modules (ii)User-defined Modules
are easy to manage, much like the examples in this
Dinesh Nagambaram (not for sales)
book. The Python solution is to place the code in
separate code groupings called modules. Built-in Functions
Dinesh Nagambaram (not for sales)
While a function is a grouping of instructions, a
module is a grouping of functions. As we know that
Built-in functions are predefined functions that are
already available in Python. Functions provide
when a program grows, function is used to simplify efficiency and structure to a programming language.
Dinesh Nagambaram (not for sales)
the code and to avoid repetition. For a complex
problem, it may not be feasible to manage the code
Python has many useful built-in functions to make
programming easier, faster, and more powerful.
Dinesh Nagambaram (not for sales)
in one single file. Then, the program is divided into
different parts under different levels, called
modules. Also, suppose we have created some
These are always available in the standard library
and for using them, we don't have to import any
module (file).
Dinesh Nagambaram (not for sales)
functions in a program and we want to reuse them
in another program. In that case, we can
Let us discuss math and datetime modules which are
one of the most commonly used built-in modules in
Dinesh Nagambaram (not for sales)
save those functions under a module and reuse
them. A module is created as a python (.py) file
Python.
To access/use any of the functions present in the
containing a collection of function definitions.
Dinesh Nagambaram (not for sales) imported module, you have to specify the name of
the module followed by the name of the function,
separated by a dot (also known as a period). This
format is called dot notation.
For example, >>>print ("The value of e is :", math.e)
import math The value of e is : 2.718281828459045
Dinesh Nagambaram (not for sales)
result =[Link] (64) ceil(x): Returns the smallest integer that is greater
than or equal to x.
sqrt() is one of the functions that belongs to math
Dinesh Nagambaram (not for sales)
module. This function accepts positive integer as an
argument and returns the square root of the
For example,
>>> print("[Link](3.4):",[Link](3.4))
argument. Thus, the above statement calls the sqrt()
Dinesh Nagambaram (not for sales)
passing 64 as an argument and returns the square
root of the number passed as the argument, i.e., 8,
Output: [Link](3.4): 4
floor(x): Returns the largest integer that is less than
Dinesh Nagambaram (not for sales)
which is then assigned to the variable 'result'.
or equal to x.
>>> [Link] (-45.17)
Dinesh Nagambaram (not for sales)
math Module
Let us understand a few more functions from the
-46
>>> [Link] (100.12)
Dinesh Nagambaram (not for sales)
math module.
100
Dinesh Nagambaram (not for sales) >>> [Link](100.72)
100
Dinesh Nagambaram (not for sales) pow(x,y): It returns the value of x', where x and y are
numeric expressions.
Dinesh Nagambaram (not for sales) >>>print("[Link](3,3):",[Link](3,3))
[Link](3, 3): 27.0
Dinesh Nagambaram (not for sales)
It contains different types of mathematical
>>>[Link](100,-2)
0.0001
functions. Most of the functions in this module
Dinesh Nagambaram (not for sales)
return float value. In order to use the math module,
we need to import it using the following statement:
>>>[Link](2,4)
16.0
Dinesh Nagambaram (not for sales)
import math #the very first statement to be given
Let us discuss commonly-used functions in math
>>>[Link](3,0)
1.0
Dinesh Nagambaram (not for sales)
module.
pi: It is a mathematical constant, the ratio of the
sqrt(x): Returns the square root of x.
Dinesh Nagambaram (not for sales)
circumference of a circle to its
diameter (3.14159 ... )
>>>print("[Link](65):",[Link](65))
[Link](65): 8.06225774829855
Dinesh Nagambaram (not for sales)
For example,
>>> print ("The value of pi is :",[Link])
>>> [Link](100)
10.0
Dinesh Nagambaram (not for sales)
The value of pi is : 3.141592653589793 >>>[Link](7)
e: It is a mathematical constant that returns e raised 2.6457513110645907
Dinesh Nagambaram (not for sales)
to the power x, where e = 2.718281. It is the base of
natural logarithms. It is also called Euler's number.
Alternatively,
>>>print("[Link](65):",round([Link](65),2))
For example,
[Link](65): 8.06 >>> [Link](-3)
-0.14112000806
Dinesh Nagambaram (not for sales)
fabs(x): Returns the absolute value of x, represented
as-
>>> [Link](0)
0.0
Dinesh Nagambaram (not for sales)
[Link] (x)
where, x can be any numeric value.
tan(x): Returns the tangent of x in radians
>>> [Link](3)
Dinesh Nagambaram (not for sales)
For example,
-0.1425465430742778
>>> print([Link](500.23))
Dinesh Nagambaram (not for sales)
500.23
>>> [Link](-3)
0.1425465430742778
>>>print([Link](-200))
Dinesh Nagambaram (not for sales)
200
>>> [Link](0)
0.0
Dinesh Nagambaram (not for sales)
>>> print([Link](-15.6343))
15.6343
help function
If you forget how to use a standard function,
Dinesh Nagambaram (not for sales)
log10(x): Returns the base-10 logarithm of x.
>>>print("math.log10(100):",math.log10(100))
Python's library utilities can help. In this case,
Python's help() library function is extremely
relevant. It is used to know the purpose of a function
Dinesh Nagambaram (not for sales)
math.log10(100): 2.0 and how it is used.
>>>math.log10(100.12) For example,
Dinesh Nagambaram (not for sales)
2.0005208409361854 >>> import math
>>>math.log10(100.72) >>>print(help([Link]))
Dinesh Nagambaram (not for sales)
2.003115717099806 Help on built-in function cos in module math:
Dinesh Nagambaram (not for sales)
cos(x): Returns the cosine of x in radians.
>>>[Link](3)
cos (x, /)
Return the cosine of x (measured in radians)
Dinesh Nagambaram (not for sales)
-0.9899924966004454
>>>[Link](-3)
None
random Module (Generating Random Numbers)
Dinesh Nagambaram (not for sales)
-0.9899924966004454 The programming concepts we have learnt so far
involved situations where we were aware of the
>>>[Link](0)
Dinesh Nagambaram (not for sales)
1.0
definite output to be obtained when a particular
task was to be executed, which is described as a
deterministic approach. But there are certain
>>>[Link] ([Link])
Dinesh Nagambaram (not for sales)
-1.0
situations/applications that involve games or
simulations which work on a non-deterministic
approach.
Dinesh Nagambaram (not for sales)
sin(x): Returns the sine of x in radians.
In these types of situations, random numbers are
extensively used such as:
Dinesh Nagambaram (not for sales)
>>>[Link](3)
0.14112000806
1. Pseudorandom numbers on lottery scratch cards.
2. ReCAPTCHA (like in login forms) uses a random
number generator to define which image is to be
shown to the user.
Dinesh Nagambaram (not for sales)
3. Computer games involving throwing of a dice,
As is evident from the above statements, each time
picking a number, or flipping a coin.
Dinesh Nagambaram (not for sales)
4. Shuffling deck of playing cards, etc.
random() generates a different number, the
random() function can also be written with the
following alternative approach:
In Python, random numbers are not enabled
Dinesh Nagambaram (not for sales)
implicitly; therefore, we need to invoke random
module explicitly or to invoke random code library
Program to calculate the sum of the digits of a
random three-digit number.
Dinesh Nagambaram (not for sales)
in order to generate random numbers. This module
contains functions that are used for generating
random numbers.
Dinesh Nagambaram (not for sales)
import statement is the first statement to be given
in a program for generating random numbers:
Dinesh Nagambaram (not for sales)
import random
The various functions associated with this module
Dinesh Nagambaram (not for sales)
are as follows:
randrange(): This method generates an integer
Dinesh Nagambaram (not for sales)
between its lower and upper argument. By default,
the lower argument is 0.
randint():
Dinesh Nagambaram (not for sales)
For example,
This function accepts two parameters, a and b, as
the lowest and highest number; returns a number
Dinesh Nagambaram (not for sales) 'N' in the inclusive range [a,b], which signifies a <= N
<= b, where the endpoints are included in the range.
This function generates a random integer number
Dinesh Nagambaram (not for sales) between two given numbers. This function is best
suited for guessing number applications. The syntax
is:
Dinesh Nagambaram (not for sales) [Link](a,b)
Dinesh Nagambaram (not for sales)
random()
Here, a is the lower bound and b is the upper bound.
In case you input a number N, then the result
generated will be a <= N <= b. Please make sure that
Dinesh Nagambaram (not for sales)
This function generates a random number from 0 to
1 such as 0.5643888123456754
the upperlimit is included in randint() function.
Dinesh Nagambaram (not for sales)
This function can be used to generate
pseudorandom floating point values. It takes no
To generate a number between 0 and 9.
parameters and returns values uniformly distributed # import the random module
Dinesh Nagambaram (not for sales)
between 0 and 1 (including 0, but excluding 1). Let
us take some examples to gain better clarity about
import random
this function: print ([Link](0,9))
Dinesh Nagambaram (not for sales)
Write a function that fills a list with numbers. (Using >>> [Link]([1,2,3,7,8,9])
randint())
5.0
Dinesh Nagambaram (not for sales) mode(): This function returns the most repeated
value of the list/sequence passed.
Dinesh Nagambaram (not for sales) Its syntax is:
[Link] (x)
Dinesh Nagambaram (not for sales) For example,
>>> import statistics
Dinesh Nagambaram (not for sales) >>> [Link]([21,24,21,45,56,67,21])
21
Dinesh Nagambaram (not for sales) >>> [Link] (("red","blue","red"))
statistics Module
Dinesh Nagambaram (not for sales)
The statistics module implements many common
'red'
statistical formulas for efficient calculations using
Dinesh Nagambaram (not for sales)
Python's various numerical types (int, float,
Decimal, and Fraction).
Dinesh Nagambaram (not for sales)
It provides functions for calculating mathematical
statistics of numeric (Real-valued) data. Before using
the functions of this module, it is required to be
Dinesh Nagambaram (not for sales)
imported first using the statement-import statistics.
The following popular statistical functions are
Dinesh Nagambaram (not for sales)
defined in this module:
mean(): The mean() function calculates the
Dinesh Nagambaram (not for sales)
arithmetic mean of the numbers in a list.
For example,
Dinesh Nagambaram (not for sales)
>>> import statistics
>>> [Link]([4,6,7,8,10,45])
Dinesh Nagambaram (not for sales)
13.333333333333334
median(): The median() function returns the middle
Dinesh Nagambaram (not for sales)
value of numeric data in a list.
This function finds the centre value, and if the data
Dinesh Nagambaram (not for sales)
set has an even number of values,
it averages the two middle items.
Dinesh Nagambaram (not for sales)
For example,
>>> import statistics
Dinesh Nagambaram (not for sales)
>>>[Link]([1,2,3,8,9])
3