Module in Python

In this tutorial, we will learn about the module in Python. Here we will learn how to create, import and use of built-in modules in Python.

What is a Module

The Python module is considered as a library file and it contains Python code with .py extension. It can contain classes, functions and variables. We can use the module to break the complexity of the large program into a small and organised file.

Types of Module in Python

  • Built-In Module
  • User Define Module

Built-In Module

There are lots of pre-defined module in Python, such as os, math, sys etc. We can find a list of built-in modules by executing help(‘modules’) command from Python Shell.

>>> help('modules')

Import Python Module

To use a function of the module, we need to import modules in our program using the import keyword.

#importing some useful module in Python
import random
import math
import sys
import platform

#randint() function of random module is generate random number
print(random.randint(1,30))

#print value of pi from math module
print(math.pi)

#system() function of platform module
print(platform.system())

#print version of Python
print(sys.version)

from and import Statement

We can import the module using from-import statement.

#import a specific function
from random import randint

#import all function of math module using *
from math import *

#randint() function of random module is generate random number
print(randint(1,30))

#print value of pi from math module
print(pi)

Aliasing Modules

We can modify the name of the module or you can say alias the name of the module using the keyword as.

#using short name for the module using aliasing
import random as rd
import math as m

#randint() function of random module is generate random number
print(rd.randint(1,30))

#print value of pi from math module
print(m.pi)

User Define – Create a Module

Creating a module in python is just like a writing a simple Python file with .py extension. We can write classes, functions and variables that can be further used in other python programs.

To begin, we will create a file, which includes multiple functions. Save this file with fun.py name (we are creating a module, called fun).

#save this file as fun.py
#function to print 1 to n.
def tolarge(n):
    for i in range(1,n+1):
        print(i)

#function to print n to 1.
def tosmall(n):
    for i in range(n,0,-1):
        print(i)

#function to print factorial.
def fact(n):
    f=1
    for i in range(1,n+1):
        f*=i
    return f

Now, create a second file test.py in the same directory, and import fun then call functions of the fun module in your program.

#import user defin module
from fun import *

#calling user define functions in other program
tolarge(5)
tosmall(5)
print(fact(5))