Always free. For everyone.
Course outline
Module 06 of 20 · Foundations

Build code people can reuse

Organise small projects with classes, clear functions, and repeatable setup. This module has 3 lessons and takes about 1h. Each lesson has a practice exercise that runs real Python in your browser and a short quiz.

Start module 06 in the Learning Lab
LESSON 1 OF 3

Keep data and behaviour together

20 minEngineering
WHAT YOU WILL DO

Model two separate sensors with one small class.

A class defines a kind of object. Each object can hold its own data and functions, called methods. Use a class when data and behaviour naturally belong together.

__init__ runs when you create an object. self refers to that particular object. Assigning self.readings = [] gives each sensor its own list.

This synthetic lab model stores readings and returns their mean. Calling sensor.add(24) uses the method on that sensor. Empty sensors return None because no mean exists yet.

See it in action

example.pyPython 3
class Sensor:
    def __init__(self, name):
        self.name = name
        self.readings = []

    def add(self, value):
        self.readings.append(value)

    def mean(self):
        if len(self.readings) == 0:
            return None
        return sum(self.readings) / len(self.readings)

sensor = Sensor("Ibadan lab A")
sensor.add(24)
sensor.add(26)
print(sensor.name, sensor.mean())
Keep this in mind

Choose a class when one object should own both values and actions.

LESSON 2 OF 3

Make a small project readable

20 minFinance
WHAT YOU WILL DO

Separate calculation from display and reject invalid inputs clearly.

Use descriptive names, short functions, and comments that explain decisions. A docstring is a quoted description at the start of a function. Capital names such as DEFAULT_RATE are a convention for constants.

raise ValueError("message") rejects an input with a useful explanation. Check invalid inputs before calculating. Keep display code outside the calculation so tests can use the returned value.

The if __name__ == "__main__": block runs when a file is executed directly. It does not run when another file imports it. This is useful when moving browser practice into reusable Python files.

See it in action

example.pyPython 3
DEFAULT_RATE = 0.10

def project_total(base_ngn, reserve_rate=DEFAULT_RATE):
    """Return a synthetic project budget including a reserve."""
    if base_ngn < 0 or reserve_rate < 0:
        raise ValueError("Cost and reserve rate must be nonnegative")
    return base_ngn * (1 + reserve_rate)

def main():
    total = project_total(20000)
    print("Planned total:", total, "NGN")

if __name__ == "__main__":
    main()
Keep this in mind

Readable code has clear inputs, explicit errors, and reusable returned results.

LESSON 3 OF 3

Make an experiment repeatable

20 minEnergy
WHAT YOU WILL DO

Generate the same synthetic sample from the same seed and record its setup.

import random gives you tools for simulated data. random.Random(seed) creates a local generator. Calling its random() method returns a value from 0 up to, but not including, 1. The same seed repeats this sequence.

range(days) supplies positions from 0 to days minus one. Our function uses them to generate a fictional daily output between 4 and 6 kWh. A fixed seed makes debugging repeatable; it does not make simulated data realistic.

For local projects, create an isolated environment in your terminal with python -m venv .venv. Record Python and package versions, input data, and seeds. Keep a requirements.txt for external dependencies, created with python -m pip freeze > requirements.txt in that environment. The browser examples here need only the standard library.

See it in action

example.pyPython 3
import random
import sys

def simulate_output(seed, days):
    generator = random.Random(seed)
    readings = []
    for day in range(days):
        readings.append(round(4 + 2 * generator.random(), 3))
    return readings

# Synthetic solar output, not a forecast
readings = simulate_output(42, 5)
print("Python:", sys.version.split()[0])
print("Seed:", 42)
print("Readings:", readings)
print("Repeatable:", readings == simulate_output(42, 5))
Keep this in mind

A useful experiment records its code, data, environment, and random seed.

ABOUT THE LEARNING LAB

Free, open and run by a nonprofit.

This page is part of Python to AI, a free course of 20 modules and 60 lessons in the engineering.fit( ) Learning Lab. The Learning Lab is built and run by engineering.fit( ), a nonprofit founded by Abdullateef Opeyemi Bakare that helps African engineering students gain research experience. You do not need an account or pay a fee to learn.

Course outline · Project lab · Visit engineering-fit.org