Python Modules
Python Modules
A module is a python file contains some variables and constants, some functions, objects etc.
defined in it, which can be used in other python programs by importing it.
There are 2 forms of import statements:
1. import <module name>
2. from <module> import <object>
To call a function of a module, the function name should be preceded with the name of the
module with a dot(.) as a separator. The syntax is as shown below:
<module name>.<function name>()
Types of Functions:
There are three types of functions in python:
1. Library Functions: These functions are already built in the python library.
2. Functions defined in modules: These functions defined in particular modules. When you
want to use these functions in program, you have to import the corresponding module of
that function.
3. User Defined Functions: The functions those are defined by the user are called user
defined functions.
Library Functions in Python:These functions are already built in the library of python. For
example: type( ), len( ), input( ) etc
Functions defined in modules:
math.pi
The mathematical constant π = 3.141592…, to available precision.
math.e
The mathematical constant e = 2.718281…, to available precision.
Q. Write the corresponding Python expressions for the following mathematical expressions.
1. Squareroot of a2+b2+c2
math.sqrt(a*a+b*b+c*c)
2. 2-ye2y+4y
2-y*math.exp(2*y)+4*y
3. p + q/(r+s)4
p+q/math.pow((r+s),4)
4. (cosx/tanx)+x
(math.cos(x)/math.tan(x))+x
5. |e2 – x|
math.fabs(math.exp(2)-x)
Random Module
It is a built-in module which contains functions that are used for generating random numbers.
In order to use the random module we need to import it using the following statement.
Import random
Commonly used functions in random module are given below:
Eg. 1.To generate a random integer number in range 15 to 35 using randint()
>>>print(random.randint(15,35))
Output: 16
2.To generate a random floating – point number between 0.0 to 1.0 simply use random()
>>>import random
>>>print(random.random())
Output: 0.022353193431
Statistics Module
The module provides functions for calculating statistics of numeric(real valued) data. It
can be included in the program by using the following statement:
import statistics
Commonly used functions available in Statistics module are: