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 ", [Link](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 ", [Link](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 of >>>[Link](49)
1 sqrt( ) a number 7.0
>>>[Link](81.3)
2 ceil( ) Returns the upper integer 82
>>>[Link](81.3)
3 floor( ) Returns the lower integer 81
Calculate the power >>>[Link](2,3)
4 pow( ) of a number 8.0
5 fabs( ) Returns the absolute value of a >>>[Link](-5.6)
number 5.6
70
>>>[Link](90)
6 sin( ) Returns the sine of a number 0.89399
>>>[Link](90)
7 cos() Returns the cosine of a number -0.448073
>>>[Link](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
S. No. Function Description Example
1 random () It returns a random float >>>[Link]()
x, such that 0 ≤ x<1 ><1
0.281954791393
2 randint(a, b) It returns a int x between >>>[Link](1,10)
a & b such that a ≤ x ≤ b
5
3 Randrange ([start,] It returns a random item >>>[Link](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
S. No. Function Description Example
1 mean ( ) It returns mean of a list of numbers >>> print([Link]([1, 3, 5, 7, 9,
11]))
6
2 median() It returns the median (middle value) of >>> print([Link]([1, 3, 5, 7,
the given data set 9, 11, 13]))
7
71
3 mode() It returns the mode (central tendency) >>> print([Link]([1, 3, 3, 3, 5,
of the given numeric or nominal data 7, 7, 9]))
set. 3
MINDMAP
MCQ
1
Study the following program and select the possible output(s) from the options (i) to (iv)
following it. Also, write the maximum and the minimum values that can be assigned to the
variable Y.
import random
X=[Link]()
Y=[Link](1,4)
print(int(X),”:”,Y+int(X))
i) 0 : 0 ii) 1 : 6 iii) 2 : 4 iv) 0 : 3
2 Observe the following program and answer the questions that follow:
import random
X=3
N=[Link](1,X)
for i in range(N):
print (i,”#”,i+1)
72