๐ฏ Lesson Objective
To learn how to use and organize code with modules and packages, making programs modular, reusable, and easier to maintain.
๐งฉ 1. What Is a Module?
A module is a Python file (.py) containing functions, variables, and classes that can be imported into other programs.
โ
Example: Using the math module
import math
print(math.sqrt(16)) # Square root
print(math.factorial(5)) # Factorial
Output:
4.0
120
โ๏ธ 2. Creating Your Own Module
- Create a file
mymodule.py:
def greet(name):
print(f"Hello, {name}!")
pi = 3.14159
- Use it in another program:
import mymodule
mymodule.greet("Sameer")
print("Value of pi:", mymodule.pi)
Output:
Hello, Sameer!
Value of pi: 3.14159
๐ 3. Importing Specific Functions
from math import sqrt, factorial
print(sqrt(25))
print(factorial(4))
โ Output:
5.0
24
๐งฐ 4. Using Aliases
import math as m
print(m.sqrt(36))
print(m.factorial(6))
Output:
6.0
720
๐งฑ 5. What Is a Package?
A package is a collection of Python modules organized in directories with an __init__.py file.
It helps structure large projects into multiple modules.
Example Structure:
my_package/
__init__.py
module1.py
module2.py
Using a module from a package:
from my_package import module1
module1.function_name()
๐ 6. Standard Library Modules
Python comes with many built-in modules:
| Module | Description |
|---|---|
os | Operating system interaction |
sys | System-specific parameters |
math | Mathematical functions |
random | Random number generation |
datetime | Date and time handling |
json | JSON data handling |
csv | CSV file operations |
โ Example: Random number
import random
print(random.randint(1, 100)) # Random integer between 1 and 100
๐ ๏ธ 7. Installing External Modules
Use pip to install external modules:
pip install requests
โ
Example: Using requests module
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
๐ 8. Real-Life Example โ Organizing Code
Create a package calculator:
calculator/
__init__.py
operations.py
operations.py:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Use in another file:
from calculator import operations
print(operations.add(10, 5))
print(operations.subtract(10, 5))
Output:
15
5

Leave a Reply