17. Introduction to the Python Standard Library
Level: Beginner–IntermediateDuration: 32m
What Is the Python Standard Library?
The Python Standard Library (PSL) is a collection of ready-made modules that come bundled with Python. Instead of writing everything from scratch, you can import these modules and save development time while writing clean, readable code.
💡 Think of the Standard Library as Python’s built-in **toolbox** – batteries included!
Why Use the Standard Library?
- No need to install extra packages
- Reliable and well-tested
- Cross-platform (works on Windows, macOS, Linux)
- Covers common use cases in real-world development
Commonly Used Standard Library Modules
1. os – Interact with Operating System
python
import os
print(os.getcwd()) # Get current working directory
print(os.listdir()) # List files in current folder2. sys – Access System-Specific Info
python
import sys
print(sys.version) # Python version
print(sys.path) # Module search path3. math – Mathematical Functions
python
import math
print(math.sqrt(49))
print(math.pi)
print(math.factorial(6))4. datetime – Work with Dates & Time
python
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))5. random – Generate Randomness
python
import random
print(random.randint(1, 10)) # Random integer
print(random.choice(['apple', 'banana', 'mango']))6. statistics – Basic Data Statistics
python
import statistics as stats
data = [1, 2, 3, 4, 5, 6]
print(stats.mean(data))
print(stats.median(data))7. collections – Advanced Data Structures
python
from collections import Counter
nums = [1, 2, 2, 3, 3, 3, 4]
print(Counter(nums)) # Count occurrences of each elementStandard Library vs Installing External Packages
| Standard Library | External Packages (pip install) |
|---|---|
| No installation required | Must install |
| Secure and official | Depends on package quality |
| Covers most common tasks | Used for advanced tasks (e.g. AI, web apps) |
Official Python Standard Library Documentation
Mini Project Step
Extend your Calculator project by adding a `statistics` utility file that uses the `statistics` module to compute mean, median, and mode. Also use `datetime` to log when each calculation happens.