Monday, September 8, 2025
HomeLanguagesImport module in Python

Import module in Python

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

import module_name

When the import is used, it searches for the module initially in the local scope by calling __import__() function. The value returned by the function is then reflected in the output of the initial code. 

PYTHON




import math
pie = math.pi
print("The value of pi is : ",pie)


Output:

The value of pi is : ', 3.141592653589793

import module_name.member_name 

In the above code module, math is imported, and its variables can be accessed by considering it to be a class and pi as its object. 
The value of pi is returned by __import__(). pi as a whole can be imported into our initial code, rather than importing the whole module. 

PYTHON




from math import pi
 
# Note that in the above example,
# we used math.pi. Here we have used
# pi directly.
print(pi)


Output:

3.141592653589793

 from module_name import * 

In the above code module, math is not imported, rather just pi has been imported as a variable. 
All the functions and constants can be imported using *. 

PYTHON




from math import *
print(pi)
print(factorial(6))


Output

3.14159265359
720

As said above import uses __import__() to search for the module, and if not found, it would raise ImportError 

PYTHON




import mathematics
print(mathematics.pi)


Output:

Traceback (most recent call last):
  File "C:/Users/GFG/Tuples/xxx.py", line 1, in 
    import mathematics
ImportError: No module named 'mathematics'

This article is contributed by Piyush Doorwar. If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.

RELATED ARTICLES

Most Popular

Dominic
32271 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6644 POSTS0 COMMENTS
Nicole Veronica
11808 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11871 POSTS0 COMMENTS
Shaida Kate Naidoo
6755 POSTS0 COMMENTS
Ted Musemwa
7030 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS