Modules in Python
Modules in Python
Topperworld.in
Modules
❖ Advantages of Modularizing
➢ Simplification: A module often concentrates on one comparatively small
area of the overall problem instead of the full task. We will have a more
manageable design problem to think about if we are only concentrating on
one module. Program development is now simpler and much less vulnerable
to mistakes.
➢ Flexibility: Modules are frequently used to establish conceptual
separations between various problem areas. It is less likely that changes to
one module would influence other portions of the program if modules are
constructed in a fashion that reduces interconnectedness. (We might even
be capable of editing a module despite being familiar with the program
beyond it.) It increases the likelihood that a group of numerous developers
will be able to collaborate on a big project.
➢ Reusability: Functions created in a particular module may be readily
accessed by different sections of the assignment (through a suitably
established api). As a result, duplicate code is no longer necessary.
➢ Scope: Modules often declare a distinct namespace to prevent identifier
clashes in various parts of a program.
©Topperworld
Python Programming
Let’s create a simple calc.py in which we define two functions, one add and
another subtract.
Example:
Syntax:
import module
Example:
import calc
print(calc.add(10, 2))
Output:
12
©Topperworld
Python Programming
Syntax:
Example:
©Topperworld
Python Programming
Output:
4.0
720
Here, sys.path is a built-in variable within the sys module. It contains a list of
directories that the interpreter will search for the required module.
Example:
# importing sys.path
print(sys.path)
©Topperworld