Modules in Python language are set of functions. After creating the functions in Modules we need to store them in .py extension file. Whenever we are in need of reusing the code, we need to import the modules and specify the function name.

Why do we use Modules in Python?

1.To break a large programs into small set of pieces.

- To incorporate Reusability.

Basically there are two types of Modules :

1.Built in Modules

2.User Defined Modules

1.Built in Modules : Python has already pre defined some of the built in Modules.

Some of the Built in Modules of Python are math, OS, random, string etc.

A.Math Example : Math function makes use of built in functions like sqrt, exp etc.

Examples on Math :

1 2 3 4 5 6 7 8 9 10 11 |
import math class Math_Example(): Z = 60.50 print(math.ceil(Z)) print (math.sqrt(Z)) print (math.exp(4)) |

OUTPUT:

Python_Modules_Math_Example

Below are the some of the Built In Methods available in Math Function.

Function Description

Ceil(x) will return the next integer number of the given number.

Sqrt(x) will return the square root of the number

Sin(x) will return sine of the given radian

Cos(x) will return cosine of the given radian

Tan(x) will return tangent of the given radian

Tan(x) Will return logarithm of e raised to power of given number.

Tan(x) will return the previous integer number.PreviousNext

B. Dir() Method : Dir() built in method will return all the available function names, when a parameter is passed.

For Example : If we are Learner in Python, then we need to pass the built in method name as parameter in Dir() folder.

1 2 3 4 5 |
import math content = dir(math) print(content) |

OUTPUT:

Python_Modules_Directory_Example

C.Random: Random module in Python will enable the user to generate the Random numbers.

Example on Random :

1 2 3 4 5 |
import random print (random.random()) print (random.randint(20,80)) |

OUTPUT:

Python_Random_Number_Example

Using from with Import :

There are scenarios where the user want to find the sqrt of a particular number. Instead of importing all the module. The user wants to import the specific method.

For Example :

1 2 3 |
from math import sqrt print (sqrt(25)) |

OUTPUT:

Python_Import_Math_Function

- User Defined Modules :

If we want to create our own modules we go for User Defined Modules.

Studentinfo.py

1 2 3 4 5 6 7 8 9 10 11 12 |
def studentInfo(id, name): print("The details of the StudentID are:",id) print("The details of the StudentName are:",name) DisplayStudentInfo.py from Modules_StudentInfo import Studentinfo Studentinfo.studentInfo(10,"student1") |

OUTPUT:

Python_UserDefined_Modules_Example

Here in the above example, DisplayStudentInfo file is accessing the methods available in Studentinfo to display the values by calling studentInfo(id, name) method.