๐ Lesson 14: Python Modules & Packages – Organize and Reuse Code
Welcome to Lesson 14! Today we’ll learn about modules and packages in Python — tools that help you organize your code and reuse it across multiple programs.
⭐ What You Will Learn in This Lesson
- Understand what modules and packages are
- Import modules in different ways
- Organize larger projects with packages
- Use popular built-in Python modules
- Create and reuse your own modules
๐ฅ Who Is This Lesson For?
- Beginners wanting cleaner code organization
- Students learning to reuse code effectively
- Anyone building medium-to-large Python projects
๐ฆ What Is a Module?
A module is a Python file that contains functions, variables, or classes that you can reuse.
# my_module.py
def greet(name):
print(f"Hello, {name}!")
PI = 3.14159
You can use it in another program:
import my_module
my_module.greet("Alice")
print(my_module.PI)
๐งฉ 1. Importing Modules
- import module_name – imports the whole module
- from module_name import function_name – imports specific items
- import module_name as alias – gives a shortcut name
from math import sqrt
print(sqrt(16)) # 4.0
import math as m
print(m.pi) # 3.141592653589793
๐ฆ What Is a Package?
A package is a folder containing multiple modules, making it easier to organize larger projects.
my_package/
__init__.py
module1.py
module2.py
๐งฉ 2. Why Use Modules & Packages?
- Reusability – write code once, use it anywhere
- Organization – keep code clean and modular
- Easy to maintain – fix code in one place
- Share with others – Python has thousands of external modules
๐งฉ 3. Popular Python Modules
- math – mathematical functions
- random – random numbers
- os – operating system operations
- datetime – date and time functions
- sys – system-related operations
๐งช Practice
- Create a module
calculator.pywith functions for add, subtract, multiply, divide, and import it into another file. - Use
mathmodule to calculate square root, factorial, and cosine of a number. - Explore
randommodule to generate a random number between 1 and 100. - Create a simple package with two modules and use functions from both modules.
- Try renaming modules with
asfor shorter code and clarity.
❌ Common Mistakes
- Importing everything with
*(can cause naming conflicts) - Not organizing large projects with packages
- Forgetting to include
__init__.pyin packages
❓ Frequently Asked Questions (FAQ)
1. Can I import multiple functions from a module?
Yes, example: from math import sqrt, factorial
2. What’s the difference between a module and a package?
A module is a single Python file, a package is a folder containing modules.
3. Can I create my own packages?
Yes, just create a folder with __init__.py and include your modules inside.
๐ What’s Next?
In the next lesson, you’ll learn about handling files in Python — reading, writing, and managing data.
Comments
Post a Comment