Skip to content
LogoAhmed Gafsi
← Back to blog

Python

Write Python functions that explain themselves

A practical guide to naming, type hints, small responsibilities, and docstrings that help learners read code with confidence.

Published 6 min read
Python symbol beside modular code blocks and a notebook
Python, one clear idea at a time. Generated editorial illustration.

Readable code is not only a professional habit. It is also a teaching tool. A well-shaped function lets a learner understand its purpose before they inspect every line.

Start with one clear responsibility

If a function validates input, transforms data, saves a file, and prints a report, its name cannot honestly describe everything it does. Split the workflow into small steps whose names tell the story.

python
def calculate_average(scores: list[float]) -> float:
    if not scores:
        raise ValueError("scores cannot be empty")
    return sum(scores) / len(scores)

Use type hints as reading aids

  • Name the action and the result, not the implementation.
  • Use type hints to make inputs and outputs visible.
  • Handle invalid input explicitly instead of returning a surprising value.
  • Add a docstring when the reason or constraint is not obvious from the code.

These habits scale beyond exercises. They make reviews faster, reduce accidental misuse, and create natural seams for testing.

Related articles

Web development7 min read

Make web forms feel fast before optimizing the backend

Four interface decisions that improve perceived speed, clarity, and trust in forms without hiding real network delays.

Read article
AI5 min read

Teach AI by starting with evaluation, not prompts

A classroom approach for turning an impressive AI demo into a measurable engineering exercise.

Read article