A module in Python is a file that contains functions, variables, and classes which you can reuse in another Python program. Importing modules helps you avoid rewriting code and use built-in or external functionality.
1οΈβ£ Importing an Entire Module
Use the import keyword.
import math
print(math.sqrt(16))
print(math.pi)
β Output:
4.0
3.141592653589793
Here:
mathβ module namesqrt()andpiβ used withmath.prefix
2οΈβ£ Import Specific Functions from a Module
You can import only the parts you need.
from math import sqrt, pi
print(sqrt(25))
print(pi)
Now you donβt need the module prefix.
3οΈβ£ Import with an Alias (Shortcut Name)
Use as to give a module a shorter name.
import math as m
print(m.sqrt(36))
Common example:
import numpy as np
4οΈβ£ Import Everything from a Module
from math import *
print(sqrt(49))
print(pi)
β οΈ Not recommended in large programs because it may create name conflicts.
5οΈβ£ Import Your Own Module
If you create a file:
mymodule.py
def greet(name):
print("Hello", name)
Then in another file:
import mymodule
mymodule.greet("Venkat")
6οΈβ£ Example with Built-in Module
Using the random module:
import randomprint(random.randint(1, 10))
This generates a random number between 1 and 10.
π Summary
| Syntax | Meaning |
|---|---|
import module | Import entire module |
from module import name | Import specific function |
import module as alias | Import with shortcut |
from module import * | Import everything |
β
Simple Tip:
Most Python programs commonly import modules like:
import math
import random
import datetime