1. What Is a Module?

A module is simply a Python file (.py
) that contains functions, classes, or variables you can reuse in other programs.
Example: mymodule.py
def greet(name):
return f"Hello, {name}!"
pi = 3.1416
Using it in another file:
import mymodule
print(mymodule.greet("Ali"))
print(mymodule.pi)
2. Importing Modules
import math
print(math.sqrt(25)) # Output: 5.0
Import specific functions:
from math import sqrt, pi
print(sqrt(49)) # Output: 7.0
print(pi) # Output: 3.141592653589793
3. Built-in vs External Modules
Type | Example | Usage |
---|---|---|
Built-in | math , os , random , datetime | Already included with Python |
External | requests , numpy , pandas | Installed with pip |
Custom | mymodule.py | Written by you |
4. Packages in Python
A package is a collection of modules organized in directories with an __init__.py
file.
Example structure:
mypackage/
__init__.py
module1.py
module2.py
Usage:
from mypackage import module1
module1.function_name()
5. Installing External Packages with pip
pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
6. Best Practices
- Organize related functions into modules.
- Group multiple modules into packages.
- Use
pip freeze
to track installed packages. - Use
virtualenv
orvenv
to manage dependencies.
Summary
- Modules = single
.py
file. - Packages = collection of modules.
- Use import to bring in built-in, external, or custom modules.
pip
helps you install external libraries.- Modular code = cleaner, reusable, and easier to maintain.
username=106688624922
password=13229551516783b75252fa5
username=123655002391
password=6738d21f29c59.16835
username=269841467456
password=66e99fb26a6dc.18591
Username: 2126021051
Password: 2223881826
username: 9368661721
Password: 8020266401