Python Modules
🐍 Python Modules
A module in Python is simply a file that contains Python code — such as variables, functions, classes, etc.
Modules help in:
Code reusability
Better organization
Avoiding duplication
Working with built-in tools
1. Using Built-in Modules
Python comes with many modules like:math, random, datetime, os, etc.
Example:
2. import Statement
There are multiple ways to import modules:
whole module
specific function
module with alias
multiple functions
3. Create Your Own Module
Create a file named: my_module.py
Now import it in another file:
4. Using from module import *
This imports everything from a module:
⚠ Not recommended for large projects because it becomes unclear what came from where.
5. Built-in Useful Modules
| Module Name | Purpose |
|---|---|
math |
Mathematical operations |
random |
Generate random numbers |
datetime |
Work with dates/time |
os |
Operating system interaction |
sys |
System-specific functions |
statistics |
Mean, median, mode |
Examples
📌 Random Module
📌 Datetime Module
6. Check What’s Inside a Module
Use the dir() function:
7. Working with Packages
A package is a group of modules stored in a folder containing an __init__.py file.
Example:
Usage:
8. Install External Modules (PIP)
Use terminal command:
Then import and use:
📌 Summary Table
| Import Type | Example |
|---|---|
| Import whole module | import math |
| Import with alias | import math as m |
| Import function | from math import sqrt |
| Import all | from math import * |
| Custom module | import my_module |
🧠 Practice Tasks
-
Create a module named
calculator.pywith add, subtract, multiply, divide functions and import it. -
Use the
randommodule to create a dice rolling program. -
Use
datetimeto print a user-friendly timestamp. -
Install an external package like
pyjokesand print a random joke.
