Python Modules
Python Modules
In this tutorial, we will be exploring Python modules. A Python module enables a programmer to store definitions in a Python file, which can be utilized in a script or a Python interactive interpreter. The definitions written inside a module can be imported into the main module using the import command.
Sometimes, a similar function can be used in multiple programs. To avoid repeatedly writing the same code, it is recommended that you create and use a module in different programs.
Create Python Module
A module can be defined with some function definition and statements. The file name can be the module name or the task it performs with the .py extension.
For example, if we design a module that computes the functions of a calculator, then the sample module name can be calc.py. Note that the module file must be saved in the same directory as the main program or where it will be imported.
Let’s create a sample Python module.
# Python module creation of a module # Python tutorials - www.TestingDocs.com def add(a, b): 'Add function' return a + b def subtract(a, b): 'Subtract function' return a - b
Import Python module
We can use the import command to import the module. The general syntax to import the module is:
import module_name
A module can be called from:
- The Python interpreter
- Another Python script file
- Another Python Function
Now, let’s import the module into a sample program and use the functions defined in the module.
# Import module Demo # Python tutorials - www.TestingDocs.com import calc num1 = input('Enter a number (a):') num1 = int(num1) num2 = input('Enter another number (b):') num2 = int(num2) print('Addition of (a + b) =', calc.add(num1, num2)) print('Subtraction of (a - b) =', calc.subtract(num1, num2))
Output
Enter a number (a):90
Enter another number (b):79
Addition of (a + b) = 169
Subtraction of (a – b) = 11
We have created a Python module, imported it into a sample program, and invoked its functions. Python modules allow for code reusability. Commonly used functions can be defined in a module and reused without writing repetitive code.
—
Python Tutorials
Python Tutorial on this website can be found at:
More information on Python is available at the official website: