Skip to content

Latest commit

 

History

History
91 lines (71 loc) · 4.17 KB

Trivedh_Python_Modules.md

File metadata and controls

91 lines (71 loc) · 4.17 KB

Modules in Python

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.

Built-in Modules

Modules which are already a part of python programming language and can be readily imported into python files are known as Built-in modules.

Examples:

  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.
  • Example

    Import OS
    os.mkdir(‘C:\\Users\\gayat\\Desktop\\module’)
    os.rmdir(‘C:\\Users\\gayat\\Desktop\\module’’)

    This will create a directory named module on desktop

  • Statistics: The statistics module provides us the functions to handle statistics of numeric data. These functions include:
    • Mean()
    • Median()
    • Mode()
    • stdev()

Example

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))

Output:
        3.9
        4.0
        6
        1.8529256146249728

Creating a Module

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.

Example

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")

Output:
 Good Morning,John

Alias name or re-naming a module

It is used to create an alias name for the module.

Example

mainmod1.py
import goodmorning as gm
a=gm.goodmorningmsg("John")
print(a)
goodmorning.py
def goodmorningmsg(name):
  print("Good Morning,"+name)

Output:
 Good Morning,John

from import Statement

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..]]

Example

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"])

Output:
33

To display a list of available modules

Type the following command in the python module.


>>>help('modules')
Output

You can find the execution of the above examples in the following files