Import a module in Python

A Python module is a separate piece of code which contains various statements and definitions. We can import a module in our program as and when required. This ensures we don’t have to write the same code multiple times. In this article, we would discuss how to import a module in our Python program.

Modules helps us make our program efficient. Such programs are easier to maintain as well. Just consider a scenario where we have to find the square root of a number. There are two ways to approach the solution – either we import a math module and use the its sqrt() function or write the entire code ourselves. We can opt either of the two. But, we believe the latter would be a bit time consuming.

Import a module in Python

Lets say we import math module to access sqrt() function. There are various ways to do it-

A. We import the module first, then we access any function available through it.

>>> import math
>>> math.sqrt(x)

B. We directly import required function (i.e. sqrt()) from the module. Other functions in math module can’t be accessed.

>>> from math import sqrt
>>> sqrt(x)

C. We have given a different module name (i.e. srt) to the math module as per our convenience.

>>> import math as srt
>>> srt.sqrt(x)

D. Lastly, * will leave function names with ( _ )  underscore in the beginning and import the rest.

>>> from math import *
>>> sqrt(x)

where, x is a variable.

Besides, we can also create and import our own modules. To illustrate, we will find the square root of a number using both built-in as well as user-defined module. Therefore, we have split the article from here –

  1. Import built-in modules,
  2. Create and Import used-defined modules.
1. Import built-in module

Lets say we intend to find the square root of 9. Then, use sqrt() function in math module. As already discussed –

>>> import math
>>> math.sqrt(9)
2. Create & Import user-defined module

In this section, we will first create a module and then access the function declared inside the module.

The filename of module will be the module name. Create a file – example.py; module name will be example.

File example.py has the following code in it –

# Module for Square root of a number

def mysqrt(x): 
	a=x ** 0.5
	return a

Now, open Python shell in the current directory i.e. where example.py in stored. And, issue the following –

>>> import example
>>> example.mysqrt(9)

In conclusion, we have discussed how to import a built-in and user-defined module in Python.