Learning Goals
3 minBy the end of this lesson you can:
- Use three import shapes:
import math,from math import sqrt,import statistics as st. - Reach for the right standard-library module: math, statistics, random, time, datetime, os, sys, csv, json, re.
- Read the Python docs page for any module — the "index of useful functions".
- Avoid the
from x import *trap.
Warm-Up · You're Already Doing It
5 minSince PY-L1-11 you've been writing this:
import random print(random.randint(1, 6))
That's an import. random is a module — a file of pre-written code that ships with Python. There are over 200 of these in the standard library. Today we look at the picture more broadly and meet three more.
If you're about to write a function that does something common — square root, average, find files, parse JSON — pause first. Someone has probably already written it, and it's already on your computer.
New Concept · Three Import Shapes
14 minShape 1 · import module
The default. You access things inside the module by typing the module name first.
import math print(math.sqrt(81)) # → 9.0 print(math.pi) # → 3.141592653589793 print(math.floor(3.9)) # → 3 print(math.ceil(3.1)) # → 4
The math. prefix is friction, but it's also clarity — a future reader instantly knows where sqrt came from.
Shape 2 · from module import name
Pull a specific function or constant into your namespace. No prefix needed afterwards.
from math import sqrt, pi print(sqrt(81)) # → 9.0 (no math. prefix) print(pi) # → 3.141592653589793
Good when you use the same name a lot. Less good if it's ambiguous — sqrt could be from math or cmath; the prefix makes it obvious.
Shape 3 · import module as alias
Rename a module on import. Used for either (a) clearer names, or (b) standard ecosystem conventions — like import numpy as np, which everyone in the data world writes.
import statistics as st scores = [82, 91, 76, 65, 88] print(st.mean(scores)) # → 80.4 print(st.median(scores)) # → 82 print(st.stdev(scores)) # → 10.21...
Avoid · from module import *
The star imports everything the module exports. Now you don't know where any of your functions came from — your open might be Python's built-in or might be requests.open.
from math import * # ❌ avoid # Now sqrt, pi, log, sin, ... all leak into your namespace.
Acceptable only in tiny throw-away scripts. Don't use it in real files.
Modules you'll meet
math sqrt, floor, ceil, pi, log, sin, ... statistics mean, median, stdev, variance, mode random randint, choice, shuffle, sample, random, seed time time(), sleep(seconds) datetime date, time, datetime, timedelta os os.path.join, os.listdir, os.remove, os.makedirs sys sys.argv (command-line args), sys.exit csv csv.reader, csv.writer (Level 4) json json.dump, json.load (PY-L2-45) re re.findall, re.search (PY-L2-42)
You'll touch most of these before Level 2 ends.
Where do imports live?
Convention: all imports at the top of the file. Standard-library first, third-party next, your own modules last. Three groups, separated by a blank line.
# stdlib import os import sys import random from datetime import date # third-party (we won't use any until Level 4) # import requests # your own modules (tomorrow's lesson) # from .my_helpers import safe_int
Worked Example · Class-Stats Reporter
12 minBuild class_stats.py. It loads a file of test scores and uses statistics + math to produce a polished report.
Save marks.txt first — one score per line:
82 91 76 65 88 73 95 58 80 71
Code
# class_stats.py — use statistics + math + random import statistics as st import math import random def load_marks(path): with open(path, encoding="utf-8") as f: out = [] for line in f: try: out.append(int(line.strip())) except ValueError: pass return out marks = load_marks("marks.txt") if not marks: print("No marks loaded.") raise SystemExit print(f"Students : {len(marks)}") print(f"Mean : {st.mean(marks):.2f}") print(f"Median : {st.median(marks)}") print(f"Stdev : {st.stdev(marks):.2f}") print(f"Range : {min(marks)} … {max(marks)}") # Math: how many sit within 1 standard deviation of the mean? mean = st.mean(marks) sd = st.stdev(marks) within = [m for m in marks if abs(m - mean) <= sd] print(f"Within 1σ : {len(within)} of {len(marks)} ({len(within) / len(marks) * 100:.0f}%)") # Random: pick a student at random to present today random.seed() print(f"Today's presenter index: {random.randrange(len(marks))}") # Math: ceiling of average (round UP for "minimum passing year-group avg") print(f"Ceil(mean) : {math.ceil(mean)}")
Sample output
Students : 10 Mean : 77.90 Median : 78.0 Stdev : 11.32 Range : 58 … 95 Within 1σ : 7 of 10 (70%) Today's presenter index: 4 Ceil(mean) : 78
Read the diff
Six lines of computation. Three modules. We didn't write a single mean, median or standard-deviation function from scratch — they came free with Python. st is statistics renamed; random.randrange(n) picks an integer 0 to n-1; math.ceil rounds up.
Try It Yourself
13 minAsk the user for a radius. Print the circle's area using math.pi.
Hint
from math import pi r = float(input("Radius: ")) print(f"Area = {pi * r * r:.2f}")
Use statistics.mode to find the most frequent score in [82, 91, 91, 76, 91, 65, 88].
Hint
from statistics import mode print(mode([82, 91, 91, 76, 91, 65, 88])) # → 91
If ties exist, mode returns the first one seen. multimode returns every winner.
Use time.sleep(1) to print "3", wait a second, print "2", wait, print "1", wait, print "GO!".
Hint
import time for i in (3, 2, 1): print(i) time.sleep(1) print("GO!")
time.sleep(seconds) pauses your program. Great for animations, retry delays, and just letting users see a message before the next one.
Mini-Challenge · Stopwatch
8 minBuild stopwatch.py. Press Enter to start. Press Enter again to stop. Print the elapsed seconds, rounded to two decimals — using time.time().
Then run it five times in a row in a small loop, store each elapsed time in a list, and use statistics.mean and statistics.stdev to print the average reaction time and how consistent it was.
Show one possible solution
# stopwatch.py — reaction-time game import time import statistics as st def one_round(target): input(f"\nReady? Press Enter, then press Enter again after {target}s. ") start = time.time() input() elapsed = time.time() - start error = abs(elapsed - target) print(f" Took {elapsed:.2f}s (off by {error:.2f}s)") return error errors = [] for r in range(5): print(f"--- Round {r + 1} of 5 ---") errors.append(one_round(3)) print() print(f"Average error : {st.mean(errors):.2f}s") print(f"Consistency σ : {st.stdev(errors):.2f}s")
Non-negotiables: time.time() bracketing the user input, a list of errors, and st.mean/st.stdev at the end. The smaller your standard deviation, the more consistent your timing — a classic test for reaction games and benchmarking code.
Recap
3 minThe standard library is hundreds of free modules. import x brings the whole module in (you write x.func()). from x import y brings a specific name in. import x as y renames on the way in. Don't use from x import * — it makes your code hard to read. Put all imports at the top of the file, grouped. Reach for stdlib first before writing your own version of mean, sqrt, sleep or randint.
Vocabulary Card
- module
- A file of pre-written Python code you can import.
- standard library
- The collection of modules that ship with Python. Always installed.
- import / from / as
- The three import shapes. Each useful in different contexts.
- from x import *
- The "star import". Pulls in everything. Avoid in real code.
Homework
4 minBuild weather_summary.py. Given temps.txt with one daily temperature per line, print a summary using the right module for each number:
statistics.meanfor the average.statistics.medianfor the median.statistics.stdevfor the standard deviation.min/max(built-ins) for hottest/coldest.math.ceilandmath.flooron the average for "rounded up" and "rounded down".random.choiceto pick a sample temperature to display.
Stretch. Add import time and print the runtime of the whole report at the bottom.
Sample · weather_summary.py
# weather_summary.py — every module pulling its weight import statistics as st import math import random import time start = time.time() with open("temps.txt", encoding="utf-8") as f: temps = [float(line.strip()) for line in f if line.strip()] print(f"{len(temps)} days loaded.") print(f"Mean : {st.mean(temps):.2f}°C") print(f"Median : {st.median(temps)}°C") print(f"Stdev : {st.stdev(temps):.2f}°C") print(f"Hottest : {max(temps)}°C") print(f"Coldest : {min(temps)}°C") print(f"Rounded up : {math.ceil(st.mean(temps))}°C") print(f"Rounded dn : {math.floor(st.mean(temps))}°C") print(f"Sample day : {random.choice(temps)}°C") print(f"\nReport took {time.time() - start:.4f}s")
Non-negotiables: four standard-library modules, one expression each, all useful. The runtime line is your first taste of micro-profiling — every project bigger than a script will use this trick.