Skip to main content

Introduction to Python Module

Modules are the pre-defined files that contain the python codes which depict the basic functionalities of class, methods, variables, etc. A module can also include runnable code.

It consists of different functions, classes in a group of files inside a directory. Modules can also be termed as Libraries. It is basically pre-defined methods that can be used to make the code more efficient and reduce redundancy.

Modules bind the code and reduce the repetitions of functions frequently used in the code. 

It makes the code much clear and easy to understand.

1. Create a Module:

We can create a module just by saving the code we want in a file with the file extension .py.

Example:

Save this code in a file with .py extension. Here we are saving it in module_1.py

def welcome(n):
    print("Hello" + n)

2. Using a Module:

We can access a module just by using import statement.

Example:

Import the module name we just created and call the welcome function:

import module_1

module_1.welcome("abc")

3. Variables in Module

 Apart from methods, classes and function. It can also contain variables of all types.

Example:

Save this code in the file module_1.py.

person = {"name":"abc","age":16,"place": "xyz"}

Now import the module named module_1.py and access the variable.

import module_1

a = module_1.person["age"]
print(a)

Output: 16

4. Built-in Modules:

There are several built-in modules in Python, which we can import whenever we want.

Example:

import math 
a = math.pow(4,3)
print(a)

Output: 64.0

Using the dir() Function

It is a built-in function to list all the function names (or variable names) in a module.

Example:

import math
dir(math)
['__doc__','__loader__', __name__','__package__','__spec__','acos','acosh','asin','asinh','atan','atan2','atanh','ceil',
'comb','copysign','cos','cosh','degrees','dist','e','erf','erfc','exp','expm1','fabs','factorial','floor','fmod','frexp',
'fsum','gamma','gcd','hypot','inf','isclose','isfinite','isinf','isnan','isqrt','ldexp','lgamma','log','log10','log1p',
'log2','modf','nan','perm','pi','pow','prod','radians','remainder','sin','sinh','sqrt','tan','tanh','tau','trunc']
Tags
Submitted by devanshi.srivastava on July 7, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.