Modules in Python
A module is simply a python file where statements,classes, Objects, functions, constants and
variables are defined. The file name is the module name with .py extension. Definitions from a
module can be imported into other modules. It is a kind of code library.
We can use the module we created, by using the import statement.
How to import modules in Python?
Python module can be accessed in any of following ways.
1. Python import statement
import math
print(“2 to the power 3 is ", math.pow(2,3))
Just similar to math ,user defined module can be accessed using import statement
2. Import with renaming
import math as mt
print(“2 to the power 3 is ", mt.pow(2,3))
3. Python from...
import statement from math import pow
print(“2 to the power 3 is ", pow(2,3))
4. Import all names
from math import *
print(“2 to the power 3 is ", pow(2,3))
Functions of math module:
To work with the functions of the math module, we must import the math module in the
program.
import math
S. No. Function Description Example
Returns the square root >>>math.sqrt(49)
1 sqrt( ) of a number 7.0
>>>math.ceil(81.3)
2 ceil( ) Returns the upper integer 82
>>>math.floor(81.3)
3 floor( ) Returns the lower integer 81
Calculate the power >>>math.pow(2,3)
4 pow( ) of a number 8.0
5 fabs( ) Returns the absolute value of >>>math.fabs(-5.6)
a number 5.6
>>>math.sin(90)
6 sin( ) Returns the sine of a number 0.89399
>>>math.cos(90)
7 cos() Returns the cosine of a number -0.448073
>>>math.tan(90)
8 tan() Returns the tangent of a number
-1.995200
Functions of random module:
To work with the functions of a random module, we must import a random module in
the program.
import random
Function Description Example
>>>random.random()
random () It returns a random float
0.281954791393
x, such that 0 ≤ x<1 ><1
>>>random.randint(1,10)
randint(a, b) It returns a int x between
5
a & b such that a ≤ x ≤ b
Randrange ([start,] It returns a random item >>>random.randrange(100,1000,3)
stop [,step]) from the given range upto 150
stop-1.
Functions of statistics module:To work with the functions of the statistics module, we must
import the statistics module in the program.
import statistics
Function Description Example
mean ( ) It returns mean of a list of >>> print(statistics.mean([1, 3, 5, 7, 9,11]))
numbers 6
median() It returns the median >>> print(statistics.median([1, 3, 5, 7,9, 11,
(middle value) of the given 13]))
data set 7
mode() It returns the mode (central >>> print(statistics.mode([1, 3, 3, 3, 5,7, 7, 9]))
tendency) of the given 3
numeric or nominal data
set.
MINDMAP