A Python module is a Python file containing a set of functions and variables to be used in an application. The variables can be of any type (arrays, dictionaries, objects, etc.)
Modules can be either:
1. Built in
2. User-defined.
To create a module, create a Python file with a .py
extension.
Modules created with a .py extension can be used in another Python source file, using the import
statement.
Here’s an example of a simple module, myModule.py
:
#myModule.pydef myFunction( parameter ): #define a function in myModule.pyprint "Course : ", parameterreturn
To call this Python module myModule.py
, create
another Python file callModule.py
file and use the import statement.
import myModule.py:myModule.myFunction(“Python Programming”)
When the Python interpreter encounters an import statement, it imports the module if it is present in the search path.
A search path is a list of directories that the interpreter searches for importing a module.
When the above code is executed, the following output is produced:
#myModule.pydef myFunction( parameter ): #define a function in myModule.pyprint ("Course : ", parameter)return
There are several built-in modules in Python, which you can import
whenever you like.
To call a built-in Module and use the function of that module write:
import moduleName #call a module
moduleName.function()#use module function
import mathprint("The value of cosine is", math.cos(3))print("The value of sine is", math.sin(3))print("The value of tangent is", math.tan(3))print("The value of pi is", math.pi)
There are a couple of key benefits of creating and using a module in Python:
Functionality defined in a single module can be easily reused by other parts of the application. This eliminates the need to recreate duplicate code.
RELATED TAGS