Python Modules

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this Python tutorial, let us learn to create and import modules in Python, different techniques to import Python modules with appropriate examples.

Introduction of Python modules

Modules refer to a file containing Python statements and definitions. A file containing Python code, is called a module and its module name would be an example.

The modules are used to break down large programs into small organized files that provides reusability of code.

Example code to create a module

# Python Module example
def add(a, b):
 """This program adds two
 numbers and return the result"""
 result = a + b
 return result

Importing modules in Python

We can import the definitions inside a module to another module or the interactive interpreter in Python.

The import keyword is used to do this. To import a previously defined module example, type the following in the Python prompt.


import example

Import statement in Python

To import a module using import statement and access the definitions inside it, use the dot operator.

Example code to import statements

# import statement example
# to import standard module math
import math
print("The value of pi is", math.pi)


The value of pi is 3.141592653589793

Python Module Search Path

While importing a module, Python looks at several places. Interpreter first looks for a built-in module then (if not found) into a list of directories defined in sys.path. The search is in this order.

  • The current directory.
  • PYTHONPATH (an environment variable with a list of the directory).
  • The installation-dependent default directory.

Example code for module search 

import sys

Leave a Comment

Your email address will not be published. Required fields are marked *