Modules In Python

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.

  1. 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 :

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.


OUTPUT:

Python_Modules_Directory_Example

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

Example on Random :


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 :

OUTPUT:

Python_Import_Math_Function

  1. User Defined Modules :

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

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.

Leave a Comment

Your email address will not be published. Required fields are marked *