Importing Modules in Python (Built-in & Custom Modules)
What is a Module in Python?
A module is a Python file (.py) that contains reusable functions, classes, or variables. Python provides two main types of modules:
- Built-in modules (e.g., math, os, random)
- Custom/user-defined modules (your own .py files)
How to Import Modules in Python
Python provides multiple ways to import modules:
Standard Import
import math
print(math.sqrt(16)) # Output: 4.0
Import Specific Items
from math import pi, pow
print(pi) # Output: 3.141592653589793
print(pow(2, 3)) # Output: 8.0
Import with Alias
import random as rnd
print(rnd.randint(1, 10))
Built-in Modules in Python
Python has a rich set of built-in modules you can use without installing anything.
Module | Purpose | Example Function |
---|---|---|
math | Math operations | sqrt(), pow() |
os | Operating system tasks | os.getcwd() |
sys | Python runtime interaction | sys.argv |
random | Random number generation | randint(), choice() |
datetime | Date & time handling | datetime.now() |
Example: Using os Module
import os
print("Current Directory:", os.getcwd())
Output:
Current Directory: /your/path/
Custom/User-Defined Modules
You can create your own module by simply writing Python code in a .py file.
Step-by-Step Example
Step 1: Create a file named mymodule.py
# mymodule.py
def welcome(name):
return f"Welcome, {name}!"
PI = 3.14159
Step 2: Import the module in another file
# main.py
import mymodule
print(mymodule.welcome("Alice"))
print(mymodule.PI)
Output:
Welcome, Alice! 3.14159
Python Import Variations
Syntax | Description |
---|---|
import module | Imports entire module |
from module import name | Imports specific item |
from module import * | Imports everything (not recommended) |
import module as alias | Imports with alias |
Importing from Packages (Custom or Installed)
from mypackage.utils import helper_function
You must ensure that:
- The package folder has an __init__.py file
- The structure is correct
Handling Import Errors
If you see ModuleNotFoundError:
- Make sure the module is in the same directory or Python path
- Check spelling and file names
- Ensure __init__.py exists in packages (for legacy compatibility)