MODULE
In a Python, a module can be defined as a python program file, which contains a python code including python functions. It is essentially a python script file that can contain variables,functions, and classes. The variables can be of any type (array, dictionaries, objects etc.)
Modules can be divided into two sub parts :-
- Built in
- User-defined
1) User-defined Modules
Create a Module:- To create a module, create a Python file with a .py
extension.
Call a Module:- Modules created with a .py extension can be used in another Python source file, using the import
statement.
#callModule.py
import myModule
myModule.myFunction("Python Programming")
2) Built-in Modules
There are several built-in modules in Python, which you can
import
whenever you like.Call a built-in Module:- 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 math
print("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)
WHY MODULES USED?
There are couple of key that describe the use of modules in python:-
Structured Code
- Code is logically organized by being grouped into one Python file which makes development easier and less error-prone.
- Code is easier to understand and use.
- Functionality defined in a single module can be easily reused by other parts of the application. This eliminates the need to recreate duplicate code.
HOW THEY ARE USED?
To create a module just save the code you want in a file with the file extension
.py
:Example
Save this code in a file named
mymodule.py
def greeting(name):
print("Hello, " + name)
Now we can use the module we just created, by using the
import
statement:Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Royal")
The Output is:- Hello, Royal
0 Comments
Please do not add any spam link in the comment box