Last Updated : 08 Mar, 2025
In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Python’s import statement is the most common way to bring in external functionality, but there are multiple ways to do it.
Importing a Module in PythonThe most common way to use a module is by importing it with the import statement. This allows access to all the functions and variables defined in the module. Example:
Python
import math
pie = math.pi
print("The value of pi is:", pie)
The value of pi is: 3.141592653589793
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.
Python
from math import pi
print(pi)
Explanation:
Python provides many built-in modules that can be imported directly without installation. These modules offer ready-to-use functions for various tasks, such as random number generation, math operations and file handling.
Python
import random
# Generate a random number between 1 and 10
res = random.randint(1, 10)
print("Random Number:", res)
Explanation:
To make code more readable and concise, we can assign an alias to a module using the as keyword. This is especially useful when working with long module names.
Python
import math as m
# Use the alias to call a function
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.
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.
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