Import a module in Python

A module is basically a file which has many lines of python code that can be referred or used by other python programs. A big python program should be organized to keep different parts of the program in different modules. That helps in all aspects like debugging, enhancements and packaging the program efficiently. To use a module in any python program we should first import it to the new program. All the functions, methods etc. from this module then will be available to the new program.

With import statement

Let’s create a file named which contains program for a specific calculation as shown below.


def getprofit(cp, sp):
   result = ((sp-cp)/cp)*100
   return result

Next we want to use the above function in another python program. We can then use the import function in the new program to refer to this module and its function named getprofit.


import profit



Running the above code gives us the following result −


With From Module Import

We can also import only a specific method from a module instead of the entire module. For that we use the from Module import statement as shown below. In the below example we import the value of pi from math module to be used in some calculation in the program.


from math import pi

x = 30*pi


Running the above code gives us the following result −


Investigating modules

If we want to know the location of various inbuilt modules we can use the sys module to find out. Similarly to know the various function available in a module we can use the dir method as shown below.


import sys
import math



Running the above code gives us the following result −

[' ',

['…..log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod',….]

Updated on: 10-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started