Part 07 / Topic 9 of 9
Standard library tour
These come with Python. No install needed.
math
import math
print(math.ceil(4.1), math.floor(4.9)) # 5 4
print(math.pow(2, 10)) # 1024.0
print(round(math.pi, 2)) # 3.14
๐ Going deeper:
math.powalways returns afloat;2 ** 10keeps anint(1024). For money, floats can be slightly off (0.1 + 0.2is0.30000000000000004); thedecimalmodule gives exact decimal maths.
random and secrets
random is for games and simulations. secrets is for security: OTPs, passwords, tokens. random is predictable, so never use it for security.
The string module gives handy ready-made text like string.digits ("0123456789") and string.ascii_letters.
Real-world example: a 6-digit login OTP.
import random
import secrets
import string
print(random.choice(["Asha", "Ravi", "Meena"])) # e.g. Ravi (lucky draw)
otp = "".join([secrets.choice(string.digits) for _ in range(6)])
print(otp) # e.g. 048213
print(len(otp)) # 6
print(secrets.token_hex(8)) # e.g. 9f86d081884c7d65
| Need | Use |
|---|---|
| Dice, shuffle a quiz, lucky draw | random.randint, random.shuffle, random.choice |
| OTP, password, reset-link token | secrets.choice, secrets.token_hex, secrets.token_urlsafe |
See examples/04_otp_generator.py.
๐ Going deeper:
randomuses a formula (the Mersenne Twister). If someone sees enough outputs they can predict the next ones.random.seed(7)makes the "random" numbers repeat every run, which is great for tests.secretsasks the operating system for unpredictable bytes and cannot be seeded.
os and sys
import os
import sys
print(os.path.join("reports", "march.csv")) # reports/march.csv (Windows: reports\march.csv)
print(os.environ.get("APP_MODE", "dev")) # dev (default when the variable is not set)
print(sys.version_info >= (3, 13)) # True (on Python 3.13+)
os.getcwd(): the current working folderos.environ: environment variables, settings your system or terminal passes to every program (good for config and secrets)sys.argv: command-line arguments,sys.exit(): stop the program
๐ Going deeper: for paths,
pathlib(Part 8) is the modern replacement foros.path. Keep secrets like API keys in environment variables, not in your code, so they never end up in Git.
datetime
Real-world example: days left until a bill is due.
from datetime import date, datetime, timedelta
today = date(2025, 3, 10)
due = date(2025, 3, 15)
print((due - today).days) # 5
print(today + timedelta(days=14)) # 2025-03-24
print(due.strftime("%d %b %Y, %A")) # 15 Mar 2025, Saturday
print(datetime.strptime("25-12-2025", "%d-%m-%Y").date()) # 2025-12-25
A date is a day, a datetime is a day plus a time, and a timedelta is a length of time (like "14 days").
| Code | Meaning | Example |
|---|---|---|
%d |
day | 05 |
%m |
month number | 03 |
%b / %B |
month name | Mar / March |
%Y |
4-digit year | 2025 |
%A |
weekday | Saturday |
%H:%M |
24-hour time | 14:30 |
strftime= date to text (f = format)strptime= text to date (p = parse)
Watch out for 29 February. date.replace(year=...) keeps the same day and month, so it fails when that day does not exist in the new year:
from datetime import date
birth = date(2004, 2, 29) # born on a leap day
try:
this_year = birth.replace(year=2025)
except ValueError: # 2025 has no 29 February (Part 6)
this_year = date(2025, 3, 1) # choose a fallback day, here 1 March
print(this_year) # 2025-03-01
See examples/05_due_date_calculator.py.
๐ Going deeper:
datetime.now()is naive: it has no time zone. For apps used across zones, usedatetime.now(timezone.utc)or thezoneinfomodule.
time
import time
start = time.perf_counter()
time.sleep(0.5) # wait half a second
print(round(time.perf_counter() - start, 1)) # 0.5
time.time(): seconds since 1 Jan 1970 (a "timestamp")time.perf_counter(): best for measuring how long code takestime.sleep(s): pause
๐ Going deeper:
time.time()follows the wall clock, which can jump (for example when the computer syncs its clock).perf_counter()never goes backwards, so the difference between two readings is always a true duration.
Done here? The practice set for Part 7 โ 7 exercises with solutions โ is on the part page.