A module is a file that contains Python code (functions, variables, classes) which can be reused in other programs.
Importing modules helps you:
- Reuse existing code
- Organize programs
- Use built-in libraries
- Save development time
WHAT IS A MODULE?
A module can be:
- A built-in Python module (like
math) - A user-defined Python file
- A third-party library
Example: math.py is a built-in module that provides mathematical functions.
1. BASIC IMPORT
import mathprint(math.sqrt(16))
Here, we import the math module and use sqrt().
Output:
4.0
2. IMPORT SPECIFIC FUNCTION
Instead of importing the whole module, you can import specific functions.
from math import sqrtprint(sqrt(25))
Now you donât need to write math.sqrt().
3. IMPORT MULTIPLE ITEMS
from math import sqrt, piprint(sqrt(9))
print(pi)
4. USING ALIAS (AS)
You can rename a module using as.
import math as mprint(m.sqrt(36))
This is useful for long module names.
5. IMPORT ALL FUNCTIONS
from math import *print(sqrt(49))
â Not recommended in large programs because it can cause name conflicts.
6. IMPORTING USER-DEFINED MODULE
Suppose you have a file named my_module.py:
def greet(name):
return "Hello " + name
In another file:
import my_moduleprint(my_module.greet("Hira"))
Both files must be in the same folder.
7. COMMON BUILT-IN MODULES
mathâ Mathematical functionsrandomâ Random numbersdatetimeâ Date and timeosâ Operating system functionssysâ System-specific parameters
Example:
import randomprint(random.randint(1, 10))
WHY IMPORT MODULES?
⢠Avoid rewriting code
⢠Keep code organized
⢠Use powerful built-in tools
⢠Build scalable applications
KEY TAKEAWAYS
⢠Use import module_name for full module
⢠Use from module import item for specific function
⢠Use as for alias
⢠Avoid import * in large projects
Importing modules is essential for writing efficient and professional Python programs.