Python Modules
π Python Modules β Full Guide
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:
β Import whole module
β Import specific function
β Import module with alias
β Import 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.
