Table of Contents
Why the Standard Library Matters
Python comes with a “batteries included” philosophy. That means when you install Python, you automatically get a large collection of ready‑made modules called the standard library.
You don’t need to install these with pip. They are already there, waiting to be imported with import.
In this chapter you will:
- See what kinds of problems the standard library can solve.
- Learn how to find useful modules.
- Practice using a few everyday modules beyond the ones that get their own sections (
math,random,datetimehave separate chapters right after this one).
This is about getting comfortable exploring and using what’s already built into Python.
What Is the Standard Library?
The standard library is a collection of modules that:
- Ship with Python (no extra install).
- Are maintained with Python itself.
- Cover many common tasks: working with text, files, dates, the internet, data formats, debugging, and more.
Some modules are tiny helpers, others are large toolkits. You import them like any other module, for example:
import math # math functions
import random # randomness
import datetime # dates and times
import os # operating system utilities
import json # JSON dataYou’ll learn specific modules over time. The important habit is: before writing a lot of code, ask “Is there a standard library module for this?”
Finding and Exploring Standard Library Modules
You don’t need to memorize the whole library. You just need to know how to look things up.
Official documentation
The official reference is:
- https://docs.python.org/3/library/
There you’ll find a big list of modules, grouped by topic. A few common groups:
- Text processing:
string,re,textwrap - File and OS:
os,pathlib,shutil,glob - Data formats:
json,csv,configparser - Utilities:
time,datetime,collections,itertools - Debugging:
logging,traceback
You don’t need to read it all; you search it when needed.
Getting help inside Python
You can ask Python itself about modules, functions, and classes.
import math
help(math) # overview of math module
help(math.sqrt) # info about a specific functionThis is useful when:
- You don’t remember exact parameter names.
- You want a short description and examples.
How to Import and Use Standard Library Modules
You’ve already seen import in the parent chapter. Here we’ll focus on common patterns that appear a lot with standard library modules.
1. Import the whole module
import math
result = math.sqrt(16)
You must use the module name (math) as a prefix.
2. Import with an alias
Shorten long names with as:
import datetime as dt
today = dt.date.today()This is common for modules with longer names.
3. Import specific names
from math import sqrt, pi
length = sqrt(25)
circumference = 2 * pi * 3
You can then use sqrt and pi directly, without math..
For beginners, it’s often clearer to use full imports (import math), because you always see where a function came from.
Commonly Useful Standard Library Modules (Beginner-Friendly)
Here are some standard library modules that are especially helpful when you’re starting out. Each one includes a simple example to show how it might be used.
You don’t need to master all of them now — treat this as a “toolbox preview”.
`os`: Working with the Operating System
os helps you interact with the system: environment variables, directories, paths, and more.
Common beginner uses:
- Finding the current working directory.
- Listing files in a folder.
import os
print("Current directory:", os.getcwd())
print("Files here:", os.listdir()) # list of names in current directory`pathlib`: Modern File Paths
pathlib provides an object-oriented way to work with file paths. It’s often nicer than manually joining strings.
from pathlib import Path
current = Path.cwd()
print("Current directory:", current)
notes = current / "notes.txt" # build a path safely
print("Will use file:", notes)
You’ll often see pathlib and os used together when working with files.
`sys`: System-specific Information
sys gives access to things like command-line arguments and the Python version.
Simple use: show which version of Python is running.
import sys
print("Python version:", sys.version)
Later, you might use sys.argv to read command-line arguments for scripts.
`time`: Simple Time Operations
time deals with time in seconds. It’s often used for:
- Pausing a program.
- Measuring how long something takes.
import time
print("Waiting for 2 seconds...")
time.sleep(2) # pause the program for 2 seconds
print("Done!")
For dates and calendars, you’ll usually prefer datetime, which gets its own chapter.
`random`: Randomness
random helps you pick random numbers or choices. It’s great for games and simple simulations.
Example: pick a random item from a list.
import random
colors = ["red", "green", "blue"]
choice = random.choice(colors)
print("Random color:", choice)
You’ll see more detail in the dedicated random section.
`math`: Math Functions
math provides mathematical functions: square roots, trigonometry, constants like $ \pi $.
Very common for any numeric work:
import math
print("Square root of 9:", math.sqrt(9))
print("Pi:", math.pi)
You’ll explore math more in its own section.
`datetime`: Dates and Times
datetime is for working with dates, times, and time differences.
Example: get today’s date.
import datetime
today = datetime.date.today()
print("Today is:", today)
You’ll learn more about datetime later in this chapter group.
Handling Data Formats: `json` and `csv`
Many programs read and write data. Two very common formats have built-in support.
`json`: JavaScript Object Notation
JSON is a common text format for structured data. json can:
- Convert Python data to JSON text (serializing).
- Convert JSON text back to Python data (deserializing).
Python → JSON string
import json
data = {"name": "Alice", "age": 30, "languages": ["Python", "JavaScript"]}
json_text = json.dumps(data)
print(json_text) # a JSON-formatted stringJSON string → Python
import json
json_text = '{"name": "Bob", "age": 25}'
data = json.loads(json_text)
print(data["name"]) # Bob
Later, you might combine json with file handling to save and load data from files.
`csv`: Comma-Separated Values
csv helps work with table-like data in .csv files (like spreadsheets exported to text).
Here’s a very small example of writing rows to a CSV file:
import csv
rows = [
["name", "score"],
["Alice", 95],
["Bob", 88],
]
with open("scores.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)And reading them back:
import csv
with open("scores.csv", "r", newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row)Text and String Helper Modules
Sometimes str methods are enough; sometimes you want extra tools from the standard library.
`string`: Predefined Character Sets
string provides useful constants:
import string
print(string.ascii_letters) # all A–Z and a–z
print(string.digits) # 0123456789
print(string.punctuation) # punctuation characters
You might combine this with random to build a password generator (like in the projects chapter).
`textwrap`: Wrapping and Indenting Text
textwrap helps format long text neatly.
Example: wrap text to a fixed width:
import textwrap
text = "Python is a powerful, easy-to-learn programming language."
wrapped = textwrap.fill(text, width=20)
print(wrapped)Collections and Iteration Helpers
These modules help you work with lists, counters, and loops in more powerful ways.
`collections`: Specialized Data Containers
collections offers useful container types. One very handy one is Counter for counting things.
from collections import Counter
letters = ["a", "b", "a", "c", "b", "a"]
counts = Counter(letters)
print(counts) # Counter({'a': 3, 'b': 2, 'c': 1})
print(counts["a"]) # 3You can use this to count words, characters, responses in a quiz, etc.
`itertools`: Extra Tools for Loops
itertools provides helpers for building advanced loops. Even beginners can use a few simple ones.
Example: create an infinite counter (be careful to stop it!)
import itertools
for i in itertools.count(start=1):
print(i)
if i == 5:
breakThis prints 1 to 5 and then stops.
Debugging and Logging Helpers
When programs grow, it’s useful to see what’s happening inside.
`logging`: Simple Logging
logging lets you record information about what your program is doing. Unlike print, you can control the level of importance and send it to files.
Very simple setup:
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Program started")
name = "Alice"
logging.debug(f"Name is {name}") # will not show with level=INFO
logging.warning("Something might be wrong")
You can start by just using print when you are new, then gradually learn logging as your programs get more complex.
`traceback`: Working with Error Traces
traceback lets you capture or format the error trace (the message Python shows when an exception occurs). This is more advanced and often combined with try/except, which you’ll see in the errors chapter.
When to Use the Standard Library vs External Libraries
The standard library is your first stop:
- If a built-in module solves your problem, you can use it without installing anything.
- It’s usually well-documented and reliable.
You use pip to install external libraries only when:
- The standard library doesn’t have the feature you need.
- Or an external library makes things drastically easier.
Examples:
- Use
json,csv,os,pathlib,datetimefrom the standard library. - Use external libraries like
requestsorpandaswhen your needs go beyond what’s built in (you’ll see examples in later chapters).
Practicing with the Standard Library
Here are some small practice ideas that focus on using built-in modules:
- File lister
- Use
osorpathlibto list all files in the current directory. - Print only files that end with
.txt. - Simple timer
- Use
timeto measure how long it takes a loop to run. - Print the elapsed time.
- Word counter
- Take a short text (as a string).
- Split it into words.
- Use
collections.Counterto count how many times each word appears. - Random password
- Use
string(letters, digits, punctuation) andrandomto generate a random password of a given length.
As you work on projects in later chapters, try to ask yourself:
“Is there a standard library module that would make this easier?”
The more often you look, the more comfortable you’ll become with this powerful toolbox.