Last Updated : 11 Aug, 2025
In Python, modules help organize code into reusable files. They allow you to import and use functions, classes and variables from other scripts. The import statement is the most common way to bring external functionality into your Python program.
Python modules are of two types: built-in modules like random and math, which come with Python, and external modules like pandas and numpy, which need to be installed separately.
Why do we need to import modules?Built-in modules can be directly imported using "import" keyword without any installtion. This allows access to all the functions and variables defined in the module.
Example:
Python
import math
pie = math.pi
print("Value of pi:", pie)
Value of pi: 3.141592653589793
Explanation:
To use external modules, we need to install them first, we can easily install any external module using pip command in the terminal, for example:
pip install module_name
Make sure to replace "module_name" with the name of the module we want to install, example: pandas, numpy, etc.
After installation, we can import the module like a regular built-in module using "import statement".
Example:
Python
import pandas
# Create a simple DataFrame
data = {
"Name": ["Elon", "Trevor", "Swastik"],
"Age": [25, 30, 35]
}
df = pandas.DataFrame(data)
print(df)
Name Age 0 Elon 25 1 Trevor 30 2 Swastik 35
Explanation:
Instead of importing the entire module, we can import only the functions or variables we need using the from keyword. This makes the code cleaner and avoids unnecessary imports.
Example:
Python
from math import pi
print(pi)
Explanation:
To make code more readable and concise, we can assign an alias to a module using as keyword. This is especially useful when working with long module names.
Example:
Python
import math as m
result = m.sqrt(25)
print("Square root of 25:", result)
Square root of 25: 5.0
Explanation:
Instead of importing specific functions, we can import all functions and variables from a module using the * symbol. This allows direct access to all module contents without prefixing them with the module name.
Example:
Python
from math import *
print(pi) # Accessing the constant 'pi'
print(factorial(6)) # Using the factorial function
3.141592653589793 720
Explanation:
When importing a module that doesn’t exist or isn't installed, Python raises an ImportError. To prevent this, we can handle such cases using try-except blocks.
Example:
Python
try:
import mathematics # Incorrect module name
print(mathematics.pi)
except ImportError:
print("Module not found! Please check the module name or install it if necessary.")
3.141592653589793 720
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4