Welcome to Day 16 of the 100 Days of Python series!
Today, we're exploring modules — the building blocks of reusable code in Python.
Modules help you organize your programs, avoid repetition, and make use of thousands of pre-written utilities in the Python Standard Library and beyond.
🧠 What is a Module?
A module in Python is simply a file that contains Python code — functions, classes, or variables — that you can reuse in other files.
Python comes with a huge collection of built-in modules (like math
, random
, and datetime
) and also lets you create custom modules.
🔧 How to Use a Module with import
To use a module, you use the import
keyword.
Example:
import math
print(math.sqrt(16)) # Output: 4.0
You're telling Python: “Hey, I want to use the math
module and its functions.”
🎯 Common Built-in Modules
Here are a few built-in modules you’ll use often:
Module | Purpose |
---|---|
math |
Math operations like sqrt , sin
|
random |
Random number generation |
datetime |
Dates and time manipulation |
os |
Interact with operating system |
sys |
Access system-specific parameters |
🛠 Different Ways to Import
1. import module
import math
print(math.pi)
2. from module import function
from math import sqrt
print(sqrt(25)) # No need to write math.sqrt
3. from module import *
(Not recommended)
from math import *
print(cos(0)) # ⚠️ May lead to namespace confusion
4. Import with Alias
import datetime as dt
print(dt.datetime.now())
🧪 Real-World Example: Random Password Generator
import random
import string
def generate_password(length):
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for _ in range(length))
print(generate_password(10))
🧰 Creating Your Own Module
You can write your own module by saving functions in a .py
file.
math_utils.py
def square(x):
return x * x
Use it in another file:
import math_utils
print(math_utils.square(4)) # Output: 16
Make sure both files are in the same directory, or use Python’s module path settings.
📁 Packages vs Modules
- A module is a single
.py
file - A package is a folder that contains multiple modules and an
__init__.py
file
You can import modules from packages like this:
from mypackage import mymodule
⚙️ Bonus: Checking Available Functions
You can check what's inside a module using:
import math
print(dir(math))
Or use built-in help:
help(math)
🧼 Best Practices
- ✅ Use
import module
orfrom module import specific_function
- 🚫 Avoid
from module import *
— it clutters the namespace - 🧱 Break large projects into reusable modules
- 🧪 Keep utility functions in a
utils.py
file
🧠 Recap
Today you learned:
- What Python modules are and why they’re useful
- How to import built-in and custom modules
- Different import methods and best practices
- Real-world use cases for
math
,random
, anddatetime
- How to build and use your own modules
Top comments (0)