Skip to main content

Programming fundamentals · Beginner · 20 min

Write readable code: names, comments and a formatter

By Padding · Updated 18 Nov 2026
Python 3.15.2 · Ruff 0.17.5 · python:3.15-slim (Debian)

You will turn a working but cryptic Python script into a readable one with clear names, named constants, small functions and useful comments, tidy it with Ruff, prove its output has not changed and leave with your own style checklist.

On this page

A program is read far more often than it is written: by you next month, by a teammate, by someone reviewing a pull request. Code that runs is not the same as code that is easy to change. The difference is mostly names, structure and a few comments in the right places, and none of it changes what the program does.

In this tutorial you start with a short Python script that works but is hard to read: one-letter names, unexplained numbers and one long function. It prints the end-of-day sales report for a small shop. You improve it in stages by hand, then hand the mechanical part (spacing, line breaks, common mistakes) to Ruff, a Python formatter and linter. After every change you run the script and compare its output with the original, character by character, so you know you changed how the code reads and not what it does.

You need Python 3.15 from install Python 3.15 and run your first script. Everything else is in the standard library, apart from Ruff, which is one download of about 10 MB.

Step 1 · Save the cryptic script and record its output

Make a folder for this tutorial and save the script you are going to improve:

Bash
mkdir -p ~/readable-demo
cd ~/readable-demo
cat > stall.py <<'PY'
import os, sys
d=[('rice',6,1200),('beans',2,950),('oil',1,3100),('sugar',5,700),('salt',3,250)]

def f(d):
    t=0
    n=0
    l=[]
    for x in d:
        a=x[1]*x[2]
        if x[1]>=5: a=a-a*0.1
        l.append((x[0],x[1],a))
        t=t+a
        n=n+x[1]
    tx=t*0.075
    g=t+tx
    for x in l:
        print(x[0].ljust(8),str(x[1]).rjust(3),'%10.2f'%x[2])
    print('-'*23)
    print('items'.ljust(12),str(n).rjust(10))
    print('subtotal'.ljust(12),'%10.2f'%t)
    print('tax'.ljust(12),'%10.2f'%tx)
    print('total'.ljust(12),'%10.2f'%g)
    m=None
    for x in l:
        if m==None or x[2]>m[2]: m=x
    print('best seller:',m[0])
    if g>=20000: print('target met')
    else: print('target missed by','%.2f'%(20000-g))
    return g

r=f(d)
PY
cp stall.py stall_original.py
python3.15 stall.py > before.txt
cat before.txt

Try to say what the script does before you read on. You can work it out, but only by tracing it: d turns out to be a list of sales, each a tuple of item name, quantity and unit price. x[1] is a quantity and x[2] a price. 0.1 is a discount for buying five or more, 0.075 a tax rate and 20000 a sales target. Every reader has to rebuild that picture from scratch.

stall_original.py is an untouched copy for later. before.txt holds the output you must keep identical. The > sends the printed report into that file instead of the screen.

Check it worked

cat before.txt prints the report:

Text
rice       6    6480.00
beans      2    1900.00
oil        1    3100.00
sugar      5    3150.00
salt       3     750.00
-----------------------
items                17
subtotal       15380.00
tax             1153.50
total          16533.50
best seller: rice
target missed by 3466.50

The amounts are in whatever currency you like; the script does not care.

Step 2 · Give every value a name that says what it is

Replace the whole file with a version that does the same work in the same order, with two kinds of change. First, every variable gets a name a reader can understand without tracing. Second, every unexplained number becomes a named constant at the top:

Bash
cat > stall.py <<'PY'
SALES = [("rice", 6, 1200), ("beans", 2, 950), ("oil", 1, 3100), ("sugar", 5, 700), ("salt", 3, 250)]

BULK_QUANTITY = 5
BULK_DISCOUNT = 0.1
TAX_RATE = 0.075
DAILY_TARGET = 20000
REPORT_WIDTH = 23


def print_report(sales):
    subtotal = 0
    items_sold = 0
    lines = []
    for name, quantity, unit_price in sales:
        line_total = quantity * unit_price
        if quantity >= BULK_QUANTITY:
            line_total = line_total - line_total * BULK_DISCOUNT
        lines.append((name, quantity, line_total))
        subtotal = subtotal + line_total
        items_sold = items_sold + quantity
    tax = subtotal * TAX_RATE
    total = subtotal + tax
    for name, quantity, line_total in lines:
        print(name.ljust(8), str(quantity).rjust(3), "%10.2f" % line_total)
    print("-" * REPORT_WIDTH)
    print("items".ljust(12), str(items_sold).rjust(10))
    print("subtotal".ljust(12), "%10.2f" % subtotal)
    print("tax".ljust(12), "%10.2f" % tax)
    print("total".ljust(12), "%10.2f" % total)
    best = None
    for line in lines:
        if best is None or line[2] > best[2]:
            best = line
    print("best seller:", best[0])
    if total >= DAILY_TARGET:
        print("target met")
    else:
        print("target missed by", "%.2f" % (DAILY_TARGET - total))
    return total


print_report(SALES)
PY
python3.15 stall.py > after.txt
diff before.txt after.txt && echo "output unchanged"

What changed, and why each change helps:

  • f became print_report. A function name is a verb phrase for what it does. d became sales, t became subtotal, n became items_sold, g became total. A good name answers "what is in here?" without a comment.
  • for x in d: with x[1] and x[2] became for name, quantity, unit_price in sales:. Unpacking the tuple into three names removes the index numbers a reader had to decode.
  • l is gone. A lone lowercase l looks like the digit 1 in many fonts, and PEP 8, Python's style guide, says never to use l, O or I as single-character names.
  • The numbers moved into constants. TAX_RATE = 0.075 says what 0.075 is, and when the rate changes there is one line to edit instead of a search through the file. Python has no true constants: writing the name in UPPER_CASE is the convention that tells readers "do not change this while the program runs".
  • m == None became best is None. is asks "is this the very same object", which is the correct test for None. == asks the object whether it considers itself equal, which a custom class can answer however it likes.
  • import os, sys is gone because nothing used either module, and r = f(d) became a plain call because nothing used r. Unused code makes readers look for a purpose that is not there.
  • Names stay in snake_case (lowercase words joined by underscores) for variables and functions, as PEP 8 recommends.

diff compares two files line by line. It prints nothing when they are identical, and only then does && run the echo.

Check it worked

The last line of output is output unchanged. If diff prints lines starting with < or > instead, a rename went wrong somewhere: compare that line of the report with the code that prints it.

Step 3 · Split the long function and add comments that explain why

print_report still does four jobs: it prices each sale, adds up the totals, finds the best seller and prints everything. Pull the first jobs out into small functions, each with a docstring, and add comments only where the code cannot speak for itself:

Bash
cat > stall.py <<'PY'
"""Print the end-of-day sales report for a small shop."""

SALES = [("rice", 6, 1200), ("beans", 2, 950), ("oil", 1, 3100), ("sugar", 5, 700), ("salt", 3, 250)]

BULK_QUANTITY = 5  # buy this many of one item to get the bulk discount
BULK_DISCOUNT = 0.1
TAX_RATE = 0.075
DAILY_TARGET = 20000
REPORT_WIDTH = 23  # 12-character label + space + 10-character amount


def price_line(name, quantity, unit_price):
    """Return one sale as a dictionary, with the bulk discount applied."""
    line_total = quantity * unit_price
    if quantity >= BULK_QUANTITY:
        line_total = line_total - line_total * BULK_DISCOUNT
    return {"name": name, "quantity": quantity, "total": line_total}


def best_seller(lines):
    """Return the name of the line that brought in the most money."""
    best = lines[0]
    for line in lines[1:]:
        # Strictly greater, so a tie goes to the item listed first.
        if line["total"] > best["total"]:
            best = line
    return best["name"]


def print_row(label, value):
    print(f"{label:<12} {value:>10}")


def print_report(sales):
    """Print each sale, the totals and the result against the daily target.

    sales is a list of (name, quantity, unit price) tuples. Returns the
    total including tax.
    """
    lines = [price_line(name, quantity, price) for name, quantity, price in sales]
    subtotal = sum(line["total"] for line in lines)
    tax = subtotal * TAX_RATE
    total = subtotal + tax

    for line in lines:
        print(f"{line['name']:<8} {line['quantity']:>3} {line['total']:10.2f}")
    print("-" * REPORT_WIDTH)
    print_row("items", sum(line["quantity"] for line in lines))
    print_row("subtotal", f"{subtotal:.2f}")
    print_row("tax", f"{tax:.2f}")
    print_row("total", f"{total:.2f}")
    print("best seller:", best_seller(lines))

    # Reaching the target exactly counts as meeting it.
    if total >= DAILY_TARGET:
        print("target met")
    else:
        print(f"target missed by {DAILY_TARGET - total:.2f}")
    return total


print_report(SALES)
PY
python3.15 stall.py > after.txt
diff before.txt after.txt && echo "output unchanged"

Go through it from the top:

  • The string on the first line is a module docstring: one sentence saying what the file is for. A triple-quoted string as the first statement of a file, function or class is a docstring. Python keeps it, and help() and editors show it.
  • price_line does one thing, and its name and docstring say what. Each sale is now a dictionary, so later code reads line["total"] instead of the mystery index line[2].
  • best_seller replaces the loop that started from None. It starts from the first line and only replaces it when a later line earned strictly more. The comment explains why the code uses > and not >=: it decides which item wins a tie, and that is the original behaviour.
  • print_row removes four near-identical print lines. Inside an f-string, {label:<12} pads the label on the right to 12 characters, the same as ljust(12). {value:>10} right-aligns the value in 10 characters, the same as rjust(10). {total:.2f} shows a number with two decimal places, so {x:10.2f} does exactly what '%10.2f' % x did.
  • print_report keeps the overview. Its docstring says what goes in and what comes out, which is what someone calling the function needs. The first line of a docstring is a one-line summary; a blank line separates any more detail.
  • sum(...) adds up the totals in one line instead of a running total inside the loop.

Notice which comments you did not write. A comment that repeats the code goes stale the first time someone changes one and not the other:

Python
total = subtotal + tax  # add tax to subtotal

That comment says what, which the code already says. The useful comments in the new file say why: why > rather than >=, why the target test uses >=, where 23 comes from. If you are tempted to write a "what" comment, try a better name first.

Check it worked

The output ends with output unchanged again. Open stall.py in your editor and read only the print_report function: you can now say what the report contains without looking at any other part of the file.

Step 4 · Install Ruff and let it format the file

Ruff is a Python linter and formatter from Astral, written in Rust and installed from PyPI like any Python package. The formatter rewrites layout (spaces, quotes, line breaks, blank lines) in one consistent style, so you never spend time on it again. Install it into a virtual environment in the demo folder, pinned to the version this tutorial uses:

Bash
python3.15 -m venv .venv
. .venv/bin/activate
pip install ruff==0.17.5
ruff --version

python3.15 -m venv .venv creates a private environment in the .venv folder, and . .venv/bin/activate makes its python, pip and ruff the ones your shell finds first. On Windows the activate command is .venv\Scripts\activate. If you use uv, uvx ruff@0.17.5 runs the same version without a virtual environment.

Now format the script, then run it again:

Bash
ruff format stall.py
python3.15 stall.py > after.txt
diff before.txt after.txt && echo "output unchanged"
ruff format --check stall.py

The formatter changed one thing. The SALES line was 101 characters, longer than Ruff's default limit of 88, so it now has one sale per line with a trailing comma after the last one. The trailing comma means adding a sale later changes one line, not two.

The formatter never changes what code does, only how it is laid out, so it is safe to run on every save. Most code editors can run Ruff for you when you save a file; the Ruff documentation lists the editor setups.

Check it worked

ruff --version prints ruff 0.17.5. ruff format stall.py prints 1 file reformatted, the diff prints output unchanged, and ruff format --check prints 1 file already formatted. At the top of stall.py you see:

Python
SALES = [
    ("rice", 6, 1200),
    ("beans", 2, 950),
    ("oil", 1, 3100),
    ("sugar", 5, 700),
    ("salt", 3, 250),
]

Step 5 · Run the linter on both versions

A linter reads code without running it and reports patterns that are often mistakes or make code harder to read. Run Ruff's linter on the untouched original and on your version. --output-format concise prints one line per problem:

Bash
ruff check --output-format concise stall_original.py || echo "ruff found problems"
ruff check --output-format concise stall.py

ruff check exits with status 1 when it finds anything, and || echo prints a message instead of stopping there.

The original gets seven reports. Ruff 0.17.5 prints them like this (other versions may word them slightly differently):

Text
stall_original.py:1:1: I001 [*] Import block is un-sorted or un-formatted
stall_original.py:1:8: F401 [*] `os` imported but unused
stall_original.py:1:12: F401 [*] `sys` imported but unused
stall_original.py:17:48: UP031 Use format specifiers instead of percent format
stall_original.py:20:32: UP031 Use format specifiers instead of percent format
stall_original.py:21:27: UP031 Use format specifiers instead of percent format
stall_original.py:22:29: UP031 Use format specifiers instead of percent format
Found 7 errors.

Each line gives the file, line, column, a rule code and a message. [*] marks problems ruff check --fix can repair for you. Search the code, for example F401, in the Ruff rules list to read why the rule exists.

Look at what the linter did not report: f, d, t, g, 0.075 and the 27-line function all passed. A tool can tell you an import is unused. Only a person can tell you that g should be called total.

Ruff's default rules leave out most pure style checks. Turn on the PEP 8 style rules (E and W) and the naming rules (N) for this folder with a pyproject.toml file, which Ruff reads automatically:

Bash
cat > pyproject.toml <<'TOML'
[tool.ruff.lint]
extend-select = ["E", "W", "N"]
TOML
ruff check --output-format concise stall_original.py || echo "ruff found problems"
ruff check stall.py

extend-select adds rule groups to the defaults instead of replacing them. The original now gets 14 reports. The new ones are the PEP 8 points that matter most when you start out:

  • E401: one import per line.
  • E701: no statement on the same line as if ...: or else:. Put the body on its own indented line.
  • E711: compare with None using is, not ==.
  • E741: no l, O or I as a variable name.

The other PEP 8 points worth knowing now are already in your file because the formatter or the names put them there: four spaces per indent level, two blank lines between top-level functions, snake_case names for functions and variables, UPPER_CASE for constants, CapWords for class names, and lines kept short. PEP 8 itself suggests 79 characters; Ruff and many teams use 88. Pick one per project and let the tool hold the line.

Check it worked

The original prints ruff found problems after its list both times: 7 reports with the defaults, 14 with the extra rules. Your version prints All checks passed! both times. Fix nothing in stall_original.py; it is there to compare against.

Step 6 · Write your personal style checklist

Tools catch layout and common mistakes. The rest is habit. Save a short checklist next to your code and read it before you share a file:

Bash
cat > STYLE-CHECKLIST.md <<'MD'
# My readable-code checklist

- Could someone guess what each name holds without reading the code around it?
- Is every number with a meaning a named UPPER_CASE constant?
- Does each function do one job I can describe in one sentence (its docstring)?
- Does each comment say why, not what? Could a better name replace it?
- Did I delete unused imports, variables and commented-out code?
- Did I run `ruff format` and `ruff check` with no reports?
- Did I run the program and check the output is still right?
MD
cat STYLE-CHECKLIST.md

Edit the list to suit you. If you work with others, agree the Ruff settings in pyproject.toml once and commit them with the code, so everyone's editor formats the same way and nobody argues about spacing in reviews. If your team writes comments in more than one language, agreeing which one to use belongs on the same list.

When you have copied the checklist and anything else you want to keep, delete the demo folder. Leave the virtual environment first:

Bash
deactivate
cd ~
rm -rf ~/readable-demo

Check it worked

cat STYLE-CHECKLIST.md prints your list. After the clean-up, ls ~/readable-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.