Search anything:

Module in Python

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

A module in Python is a library which is a collection of various utilities/ functions which can be loaded in external Python code and used accordingly. For example: One module in Python is string which is extensively used for handling strings. Note that the same operations can be done with the module but will take more time to implement as all basic operations need to be supported.

One can think of this as header files in C/ C++ or libraries in Java. The advantage of modules in Python is that one can import a small part of the module as well which is not possible in all languages like Java and C++.

Module is a python code (saved as '.py' file) and generally have definition of classes, variables, constants and functions. A module can be access by using import function. Anyone can create modules or can use the modules which are present by default called as built-in modules. The general attribute of module in python is given as below,

module.function (argument if any)

For creating a module we just have to first create a text file then save it using .py extention. This module can be access by typing the following commands in the python interpreter,

>>> import module

Here the word module in the command will be the file name which we want to access. We will cover the following points:

  • Prominent built-in modules in Python
  • Custom Python module
  • 3 built-in modules: os, random, math

Prominent built-in modules in Python

  1. builtin: This module contains built-in functions which are automatically available in all Python modules. You usually do not have to import this module; it is loaded automatically when the interpreter starts.
  2. exceptions: This module provides the standard exception hierarchy. It is automatically imported when Python starts. An exception is an event that occurs during the execution of a program and disrupts the normal flow of the program's instructions. An exception is a Python object that represents an error.
  3. os: This module provides a unified interface to a number of operating system functions.
  4. string: This module contains a number of functions for string processing.
  5. re: This module provides a set of powerful regular expression facilities. A Regular Expression (RegEx) allows powerful string search and matching for a pattern in a string.
  6. math: This module implements a number of mathematical operations for floating point numbers. These functions are generally thin wrappers around the platform C library functions.
  7. cmath: This module contains a number of mathematical operations for complex numbers.
  8. sys: This module provides functions and variables used to manipulate different parts of the
    Python runtime environment.
  9. time: This module provides functions to deal with dates and the time within a day. It wraps the C runtime library.
  10. gc: This module provides an interface to the built-in garbage collector.

Custom Python module

Now,lets learn to create a module of our own and run it with python interpreter. Here we have written a python code for welcome as well as for calculating the average of 3 numbers using functions and saved the file with name welcome.py. After saving the file for accessing our module, type >>>import filename in the IDLE, in our case the file name is welcome, so we will give command as >>>import welcome. This will import our python code.

def Hello(name):
    print("Hello {}. Welcome to Opengenus Internship task.".format(name))
you=input('Enter your name')
def average(num1,num2,num3):

For executing the function within the code the syntax is:


In our case the function name is average, So the command will be


This is how anyone can create a module of their own choice in python.


>>>import welcome
Enter your name Gaurav
Hello Gaurav. Welcome to Opengenus Internship task.

We will now learn more about three modules in python which are os, random and math.

os module

Functions in os module are used for performing operating system related tasks such as creating a directory, changing its path, listing the content in the directory and removing a directory. Some commonly used functions in th os module are,
a. mkdir() - Create a directory
b. chdir() - Change current working directory
c. getwd() - Get the current working directory
d. rmdir() - Remove directory
e. listdir() -List the content of current directory
Note: For using any module in python first import that module using python interpreter.
Here we have import the os module, we have created a directory using mkdir function of os module. we have changed the current directory using function in module.

>>>import os

For removing a directory we first have to change the current working directory, as we can not remove the directory on which we are working.

>>> os.rmdir("d:\\opengenus")
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'd:\\opengenus'
>>> os.chdir("d:\\")
>>> os.getcwd()
>>> os.rmdir("d:\\opengenus")

random module

Function in random module depend on the sudo random number generator function random.Some common functions of this modules are as below,
a. random() - This function generates a random float number between o.o to 1.0
b. randint() - This function returns a random integer between the specified integer.
c. randrange() - It returns a randomly selected element from the range which have variables such as start, stop and step.
d. choice() - Retuens a randomply selected element from the non-empty sequence.
e. shuffle() - This randomly reorders element in the list.

>>> import random
>>> random.random()
>>> random.randrange(10,60,5)
>>> random.randint(5,15)
>>> random.choice("algorithm")
>>> numbers=[10,20,30,40,50]
>>> random.shuffle(numbers)
>>> numbers
[30, 50, 20, 10, 40]
>>> random.choice(numbers)

math module

This module in python defines some constants as well as functions such as logarithmic, trigonometric and represenation. These are explained below,

a. Constants:
The math module defines two constants such as pi and euler's number.

>>> import math
>>> math.pi
>>> math.e

b. Trigonometric function:
This function is used for trigonometric ratios for given angle. The trigonometric function need radians as an argument. So the function degrees and radians are used here. Similarly for getting sine and cosine angles, first we convert it in 30 radians and then use the function.

>>> import math
>>> math.radians(180)
>>> math.degrees(3*math.pi)
>>> math.radians(30)
>>> math.sin(math.radians(30))
>>> math.cos(math.radians(30))
>>> math.tan(math.radians(30))

c. Logarithmic function:
This function contains log function, power function, exponential function, square root function etc.

>>> import math
>>> math.log(20)
>>> math.log10(32)
>>> math.log10(100)
>>> math.exp(5)
>>> math.pow(3,5)
>>> math.sqrt(144)
>>> math.sqrt(625)

d. Representation function:

This function contains ceil and floor function. The ceil function round off the floating integer to smallest greater than or equal integer, also the floor function returns the largest smaller than or equal integer to the given floating number.

>>> import math
>>> math.ceil(7.2)
>>> math.ceil(7.9)
>>> math.floor(15.4)
>>> math.floor(15.8)

This is how the modules are used for arranging the python code. These modules makes the task simpler as well as saves time.

Module in Python
Share this