All coding lessonsLesson 10 of 10

Modules, Classes and Next Steps

Structuring bigger programs and where to go from here

Modules and imports

import math
from random import randint, choice
import statistics as stats

print(math.sqrt(144), math.pi)
print(randint(1, 6), choice(["a", "b"]))
print(stats.mean([1, 2, 3, 4]))

A module is simply a .py file. Any file you write can be imported by another file in the same folder. The standard library ships with hundreds of them: math, random, datetime, json, os, pathlib, csv, re, statistics.

# helpers.py
def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

# main.py
from helpers import celsius_to_fahrenheit
print(celsius_to_fahrenheit(21))

if __name__ == "__main__":
    print("run directly, not imported")

Classes: your own data types

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def passed(self):
        return self.grade >= 50

    def __str__(self):
        return f"{self.name} ({self.grade})"

ada = Student("Ada", 91)
print(ada, ada.passed())

A class is a blueprint; an object is one instance built from it. __init__ is the constructor and runs automatically at creation. self refers to the instance being worked on and is always the first parameter of an instance method.

Third-party packages

python -m venv .venv        # create an isolated environment
pip install requests        # install a package
pip freeze > requirements.txt

A virtual environment keeps each project's dependencies separate, so upgrading a library for one project never breaks another.

Where to go next

  • Automation: os, pathlib and csv to tidy files and spreadsheets.
  • Data science: NumPy, pandas and Matplotlib.
  • Web: FastAPI or Django for backends, requests for APIs.
  • Testing: pytest, so changes never silently break old behaviour.
  • Build small projects — a quiz, a budget tracker, a scraper. Reading alone never makes a programmer.
Ask Teacher Smith questions about this Python lessonOpens your AI tutor with a question about “Modules, Classes and Next Steps” →