Beginner · Lesson 33 of 94

The standard library tour

Watch this lesson

View full playlist ↗

Read the lesson

What you'll learn

Concept

Python ships with about two hundred modules, and the phrase "batteries included" means most everyday problems already have a solution one import away. Before you search PyPI for a package, check whether the standard library has it. The answer is yes surprisingly often, and the standard library is tested, documented, and installed everywhere Python is, with no dependency to pin.

Problem Module The function you want first
square roots, rounding, constants math sqrt, floor, ceil, pi
random choices and shuffles random choice, shuffle, randint, seed
averages and spread statistics mean, median, stdev
measuring time, pausing time perf_counter, sleep
environment variables, process info os environ, getpid, cpu_count
the interpreter itself, arguments sys argv, exit, version
letters, digits, punctuation sets string ascii_letters, digits

math covers everything a calculator does and a few things it does not: math.isclose is the correct way to compare floats, math.floor and math.ceil round down and up, and math.inf is a value larger than any number, useful as the starting point when you search for a minimum. statistics takes a collection and gives you mean, median, and stdev without you writing the loop.

random is for games, sampling, and tests, not for security; there is a secrets module for passwords and tokens. The function to know about first is random.seed(n): it makes the "random" sequence repeatable, which is how you test code that uses randomness and how the examples in this lesson produce the same output every time they run.

The standard library tour: random.seed(42) → choice, shuffle, randint → same sequence every run → no seed → different sequence every run
The standard library tour · Figure 1 · Open for full size

time.perf_counter() is the clock for measuring how long code takes; time.sleep(seconds) pauses. os.environ is a dictionary of environment variables, which is how configuration reaches a program in production, and sys.argv is the list of command-line arguments the program was started with. sys.exit(code) ends the program with a status the shell can read: zero for success, anything else for failure. These three modules are how a script stops being a toy and starts behaving like a real command.

When a problem is new to you, the search order is: the standard library index in the documentation, then help() on a module you suspect, then PyPI. Reading the module index once, only the names, plants enough seeds that you will later remember "there was something for that". The rest of this course uses datetime, json, csv, pathlib, collections, itertools, argparse, subprocess, logging, re, and sqlite3, each in its own lesson.

The standard library tour: new problem → import it, no install, no pin → help(module) / docs index → search PyPI, pin the version
The standard library tour · Figure 2 · Open for full size

Code

Numbers: math for the calculator functions and the float comparison that actually works, statistics for the summary you would otherwise loop for.

# numbers_demo.py
import math
import statistics

print(math.sqrt(2), math.pi)
print(math.floor(3.7), math.ceil(3.2))
print(0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print(math.inf > 10 ** 100)

scores = [72, 95, 58, 88, 61]
print(statistics.mean(scores), statistics.median(scores))
print(round(statistics.stdev(scores), 2))
Output
1.4142135623730951 3.141592653589793
3 4
False True
True
74.8 72
16.3

Randomness made repeatable. With the seed set, every run of this file prints exactly this, which is what lets a lesson show real output.

# dice.py
import random

random.seed(42)

print(random.randint(1, 6), random.randint(1, 6))
print(random.choice(["rock", "paper", "scissors"]))
deck = ["A", "K", "Q", "J", "10"]
random.shuffle(deck)
print(deck)
print(random.sample(range(1, 50), 6))
Output
6 1
rock
['J', '10', 'A', 'K', 'Q']
[48, 7, 44, 35, 6, 38]

The clock, the environment, and the interpreter. perf_counter times a pause, os.environ reads a variable set for this run, and sys.argv shows the program's own name first.

# system.py
import os
import sys
import time

start = time.perf_counter()
time.sleep(0.05)
elapsed = time.perf_counter() - start
print("slept at least 50 ms:", elapsed >= 0.05)

os.environ["APP_MODE"] = "demo"
print(os.environ.get("APP_MODE"), os.environ.get("NOT_SET", "default"))
print(os.cpu_count() >= 1)

print(sys.argv[0].endswith("system.py"), len(sys.argv))
print(sys.version_info.major, sys.version_info.minor)
Output
slept at least 50 ms: True
demo default
True
True 1
3 14

string and a taste of secrets: the character sets you would otherwise type by hand, and the right way to make a token.

# strings_tokens.py
import secrets
import string

print(string.ascii_lowercase)
print(string.digits, string.punctuation[:8])
alphabet = string.ascii_letters + string.digits
token = "".join(secrets.choice(alphabet) for _ in range(16))
print(len(token), all(ch in alphabet for ch in token))
Output
abcdefghijklmnopqrstuvwxyz
0123456789 !"#$%&'(
16 True

Try it yourself

Create toolbox.py. Seed random, roll two dice ten times, and store the totals. Print the mean and median with statistics, the highest total with max, and whether any roll was a double six. Time the whole thing with perf_counter. Then read an environment variable called PLAYER with a default of "anonymous" and print a greeting; run the script twice, once with PLAYER=you set in the shell.

Common mistakes

What's next

You know what is in the box. Next you start the biggest idea in the Beginner level: object-oriented programming, beginning with what objects and classes actually are.

Course overview