Phase 1 · Programming Fundamentals
Modules, Imports & Standard Library
Organize code with imports, reuse the standard library, and structure projects into modules.
On this page
Import styles
A module is a Python file (or package) you can import. Three common styles:
- import math — then math.sqrt(9)
- from math import sqrt — then sqrt(9)
- import math as m — a short alias
import math
print(math.pi)
print(math.sqrt(16))
from random import choice, randint
print(choice(["train", "val", "test"]))
print(randint(1, 6))
import json as js
print(js.dumps({"ok": True}))Avoid from module import * — it clutters your namespace and hides where names come from.
Standard library favorites
Before installing a package, check whether the stdlib already solves it. These show up constantly:
math, random, statistics, json, datetime, pathlib (locally), collections, itertools, re.
import math
import statistics
from datetime import datetime
values = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.mean(values))
print(statistics.median(values))
print(math.ceil(2.1), math.floor(2.9))
print(datetime.now().strftime("%Y-%m-%d %H:%M"))import json
user = {"name": "Ada", "skills": ["python", "git"]}
text = json.dumps(user, indent=2)
print(text)
data = json.loads(text)
print(data["skills"][0])json is how most APIs and config files talk—get comfortable with dumps (to text) and loads (from text).
Your own modules (local projects)
On your machine, helpers.py next to main.py can be imported with import helpers if you run from that folder.
Use if __name__ == "__main__": so a file can be both imported and run as a script.
# imagine this is greeter.py
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("Ada"))
# another file could: from greeter import greetIn the browser Try It panel you stay in one file—practice stdlib imports there, and create multi-file modules in VS Code.
Packages vs modules (preview)
A package is a folder of modules (often with __init__.py). pip installs third-party packages into your venv.
You already used venv on Day 7—tomorrow’s debugging day still uses only stdlib; project days may add small libraries later.
my_app/
main.py
utils/
__init__.py
text.py
requirements.txt
.venv/Practice
Mini challenge: experiment logger
Build a small script that creates a dict with experiment name (input), a random seed (randint), mean of [0.8, 0.82, 0.79], and a timestamp string. Print it as indented JSON.
import json
import statistics
from random import randint
from datetime import datetime
name = input("Experiment name: ")
record = {
# TODO: name, seed, mean_score, created_at
}
print(json.dumps(record, indent=2))
Interactive
Try It in the browser
Powered by Pyodide
Use math.sqrt and statistics.mean on nums = [4, 9, 16, 25]. Print the square root of the mean, rounded to 2 decimals.
Output
—
Errors
—
Check understanding
Lesson quiz
Score 4/5 or higher to mark this day complete.