Import module in Python (original) (raw)

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.

Table of Content

Importing a Module in Python

The 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)

`

Output

The value of pi is: 3.141592653589793

**Explanation:

Importing Specific Functions

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:

Importing Built-in Modules

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:

Importing Modules with Aliases

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)

`

Output

Square root of 25: 5.0

**Explanation:

Importing Everything from a Module (*)

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

`

Output

3.141592653589793 720

**Explanation:

Handling Import Errors in Python

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.")

`

Output

3.141592653589793 720

**Explanation: