Module can be termed as a file containing a set of functions,classesor variables. Grouping related code into a module makes it easy to keep a track of the code.
In real time scenarios,It is really a tedious task to write the complete code of a project in a single file. Therefore, the project can be fragmented into various modules, which facilitates the user to keep track of the code and eases the task to correct the errors if any.
Modules which are already a part of python programming language and can be readily imported into python files are known as Built-in modules.
Platform,OS,SYS,RANDOM,etc.- OS: OS module is a python module that helps us to perform many operating system related tasks. The OS module in Python provides functions for creating, removing a directory (folder), fetching its contents, changing and identifying the current directory, etc. Import OS
- Statistics: The statistics module provides us the functions to handle statistics of numeric data. These functions include:
- Mean()
- Median()
- Mode()
- stdev()
os.mkdir(‘C:\\Users\\gayat\\Desktop\\module’)
os.rmdir(‘C:\\Users\\gayat\\Desktop\\module’’)
This will create a directory named module on desktop
import statistics as st
List1=[1,2,3,4,5,6,6,3,2,4]
print(st.mean(list1))
print(st.median(list1))
print(st.mode(list1))
print(st.stdev(list1))
4.0
6
1.8529256146249728
A module can be created by saving the code you want in a file with .py extension. Any name can be given to the module.
goodmorning.py |
---|
def goodmorningmsg(name): print("Good Morning,"+name) |
Use a keyword "import" to import the module into the current workspace.
mainmod.py |
---|
import goodmorning goodmorning.goodmorningmsg("John") |
Good Morning,John
It is used to create an alias name for the module.
mainmod1.py |
---|
import goodmorning as gm a=gm.goodmorningmsg("John") print(a) |
goodmorning.py |
---|
def goodmorningmsg(name): print("Good Morning,"+name) |
Good Morning,John
The "from module import function" statement is used to import a specific function from a Python module. Instead of importing the complete module ,the user could import only the necessary function.
Syntax |
---|
from modulename import name1[,name2[,name3..]] |
greetings.py |
---|
def greetings(name): print("Hello How are you?," +name) student1={"name":John,"age":20,"id":33} |
mainmod2.py |
---|
from greetings import student1 print(student["id"]) |
33
Type the following command in the python module.
>>>help('modules')