COGNITION FOUNDRYLEARN. BUILD. UNDERSTAND.
PY-018 / Organise and prove code◷ 24 min read + practice

Modules, imports and first tests

As programs grow, putting every function in one file becomes awkward. A module is a Python file or built-in extension that groups definitions. We can import library modules in the browser; creating your own multi-file project is an exercise for your local Python installation.

By the end, you can: Use import/from import, write simple assert-based checks, and distinguish browser playground imports from local multi-file projects.
Before this lesson: PY-017 · PY-015

Import the standard library

import math gives access to names such as math.isqrt and math.pi. from math import isqrt brings one named object directly into the current namespace. The module name in math.isqrt helps show where the function came from.

Python includes a large standard library for maths, data processing, dates, paths and more. Some modules depend on operating-system capabilities and do not work inside a browser sandbox. Treat a browser error as an environment limitation to investigate, not a sign the module never exists.

Your own files can become modules

On your own computer you might save calculations.py containing def double(value): return value * 2, then write from calculations import double in a different .py file. Python must be able to find the file on its import path. Filename collisions with built-in modules can confuse imports.

The browser editor is isolated from folders on your computer. Practise standard-library imports here first, then create the two-file example locally and use it to understand how your own modules are imported.

Start testing with a clear assertion

assert double(4) == 8 checks a condition and raises AssertionError if it is false. It can be a helpful first experiment, but production test suites should use proper testing tools such as Python’s unittest or pytest.

Assertions are for checking programmer assumptions in development, not validating untrusted user input. Python can disable assert statements under optimised execution (-O); user-input checks belong in ordinary if statements that raise appropriate exceptions.

Test the boundary, not just the easy case

A strong test set includes typical values, boundary values and invalid inputs. If you build a function for numbers, think about zero and negatives. If it accepts a list, consider an empty list.

When a test fails, first verify the expected result is correct, then inspect the implementation. Never change expected values solely to make a red test turn green. A trustworthy learning example is a small version of that same engineering practice.

Make your own two-file Python module

The browser editor can import standard-library modules. To practise an import between two files you create, put the following two files in the same folder on your computer. Read the source and copy each file separately, or download both together as a ZIP.

calculations.py
"""Your first reusable module — lesson PY-018."""

def double(value):
    return value * 2

def add_fee(total, fee):
    return total + fee

use_calculations.py
"""Run alongside calculations.py: py -3 use_calculations.py"""
from calculations import double, add_fee

result = double(8)
print("Doubled:", result)
print("With fee:", add_fee(result, 2))

To create the files yourself, paste each code panel into a plain-text editor. Save with the exact displayed filename and UTF-8 text encoding, not a .txt extension. Keep both files in the same directory. In a terminal opened in that directory, run py -3 use_calculations.py on Windows or python3 use_calculations.py where available.

The output should be Doubled: 16 and With fee: 18. Change double(8) and run it again to understand what the imported functions do.

If you prefer not to assemble the two files manually, download both Python files together (.zip). Inspect the source before running it.

Try it yourself.

Choose a starting example or write something completely different. You control the code; the Run button executes what is in the editor, not a hidden preset.

CF Python PlaygroundBrowser-based Python
Ready to load Python
Import a library module

Call integer-square-root and inspect the documented namespace.

Syntax colours highlight Python code. Tab inserts four spaces; press Escape then Tab to leave the editor. Ctrl+Enter runs the current code.
OUTPUT / ERRORS
Press Run Python to execute the editable code.
NOW MAKE IT YOURS

Change 81 to 80. Why does isqrt return a whole number?

Need a hint?

isqrt gives the floor of the non-negative integer square root.

On first Run, a pinned Python runtime downloads from jsDelivr. Code executes locally in your browser's Web Worker, not on our server. It cannot inspect your normal PC files or Windows hardware. Avoid entering secrets. Heavy/infinite loops are stopped by a time limit.

Check your understanding.

Try answering each question before opening its reference answer. Explain the idea aloud or change an example to test it for yourself.

  1. What is the difference between import math and from math import isqrt, and when might the first be clearer?

    View answer

    import math binds the module name so you use qualified calls such as math.isqrt(81). from math import isqrt binds that selected name directly, allowing isqrt(81). The qualified form is often clearer when reading unfamiliar code because the source module remains visible and collisions between same-named functions are less likely.

  2. Why is assert unsuitable as the only way to validate input in an application?

    View answer

    An assert statement is designed to check assumptions during development and testing. Python may remove assertions when running with optimisation (-O), so important validation could disappear. To reject a user-supplied invalid value reliably, use an ordinary condition such as if percent < 0: raise ValueError(...). Testing checks whether that rule works; it does not replace the rule.

Where this leads.

You can now define, combine, validate, organise and test small functions. Later lessons will apply these skills to real files, structured data and time.