Import a module in Python

PythonServer Side ProgrammingProgramming

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 profit.py which contains program for a specific calculation as shown below.

Example

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.

Example

import profit

perc=profit.getprofit(350,500)
print(perc)

Output

Running the above code gives us the following result −

42.857142857142854

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.

Example

from math import pi

x = 30*pi
print(x)

Output

Running the above code gives us the following result −

94.24777960769379

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.

Example

import sys
import math

print(sys.path)
print(dir(math))

Output

Running the above code gives us the following result −

[' ',
'C:\\Windows\\system32\\python38.zip',
'C:\\Python38\\DLLs',
'C:\\Python38\\lib',
'C:\\Python38',
'C:\\Python38\\lib\\site-packages']

['…..log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod',….]
raja
Published on 10-Jul-2020 14:31:30
Advertisements