Python Standard Library
In this page:
The os and sys Modules
The os module lets you interact with the filesystem and operating system (listing directories, joining paths, reading environment variables), while sys exposes interpreter-level details like command-line arguments and the module search path -- together they're the bridge between your script and its environment.
Example: The os and sys Modules
import os
import sys
print(os.getcwd()) # current working directory
print(sys.platform) # identifies the operating system
The datetime Module
The datetime module provides date, time, and datetime objects for representing points in time, plus timedelta for representing durations -- it handles the surprisingly tricky arithmetic of adding days across month boundaries or comparing two dates correctly.
Example: The datetime Module
from datetime import datetime, timedelta
now = datetime(2024, 1, 1)
print(now + timedelta(days=10)) # timedelta handles the date arithmetic correctly
The random Module
random.random() and random.randint() generate pseudo-random numbers, and random.choice()/random.shuffle() work directly on sequences -- useful for anything from simulating dice rolls to shuffling a quiz question order, though it's not cryptographically secure.
Example: The random Module
import random
print(random.randint(1, 6))
The json Module
json.dumps() converts a Python dict or list into a JSON-formatted string (encoding), and json.loads() does the reverse, parsing a JSON string back into native Python objects -- this is the standard way Python programs talk to web APIs that exchange JSON.
Example: The json Module
import json
data = {"name": "Alex"}
text = json.dumps(data) # dict -> JSON string
print(text)
print(json.loads(text)) # JSON string -> Python object again
The math Module
The math module supplies functions standard arithmetic operators don't cover, like math.sqrt(), trigonometric functions, math.log(), and rounding helpers like math.floor()/math.ceil() -- reach for it whenever you need more than +, -, *, and /.
Example: The math Module
import math
print(math.sqrt(16)) # square root
print(math.floor(4.7)) # rounds down
print(math.ceil(4.2)) # rounds up
- Guessing a function name instead of checking the docs, such as
random.randInt(), which raisesAttributeErrorbecause the function israndint. - Forgetting to
importthe module first, sodatetime.now()raisesNameError. - Using
from datetime import datetimeand then writingdatetime.datetime.now(), which fails because the name is already the class.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: