Command Palette

Search for a command to run...

Hectal
PHASE 1Beginner ~25 min· topic 11 of 11

Topic 1.11

Comments, Names and PEP 8

In one line

A comment is a note for human readers that Python ignores. Good code is mostly readable names, with comments explaining *why*. PEP 8 is Python's shared style guide (four-space indents, snake_case names, CAPITAL constants), and tools such as Ruff apply it automatically.

Think of it like this

A note in a recipe margin. "Use less salt: Grandma's tip." The note does not change the recipe, but it helps the next cook. A comment is a margin note in code: it starts with #, runs to the end of the line, and Python ignores it completely.

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

Comment
A note starting with # that Python ignores.
Docstring
A triple-quoted string at the start of a file, function or class that describes it.
PEP
Python Enhancement Proposal: a numbered design document. PEP 8 is the style guide.
Style guide
A set of agreed rules for how code should look.
Constant
A value that should not change, named in ALL_CAPS by convention.
Convention
A habit that the community follows even though the language does not force it.
Formatter
A tool that rewrites code into a standard layout.
Linter
A tool that reads code and warns about likely mistakes and style problems.

Step by step

01Comments with #

A comment can have its own line or follow code on the same line. Python skips everything from # to the end of the line. Use two spaces before an end-of-line # and one space after it, as PEP 8 asks.

To disable a line temporarily while you test, put # in front of it. This is called commenting it out. Delete such lines before you share your code.

main.pywhole filepython
# Calculate the price of an item including GST.
GST_RATE = 0.18  # 18 percent, fixed by law, so written in CAPITALS

price = 200
tax = price * GST_RATE
total = price + tax

# Show the answer with two decimals.
print(f"Total with tax: {total:.2f}")

02Why, not what

Compare two versions of the same line. The first comment repeats the code. The second tells the reader something they could not guess. Good comments are rare and valuable, like good road signs.

main.pywhole filepython
count += 1          # add 1 to count            (useless)
retries += 1        # the server sometimes drops the first call   (useful)

03Better names beat comments

A comment can fix a bad name, but a good name fixes the problem at its source. Every place that uses the variable gets the benefit, and the name cannot go out of date the way a comment can.

main.pywhole filepython
# before: needs a comment
d = 7        # days in a week

# after: no comment needed
DAYS_IN_WEEK = 7

04The module docstring

A string that is the first statement in a file becomes its docstring. Python keeps it in the special name __doc__ (double underscores on both sides are called dunder, short for "double underscore"). print(__doc__) shows it. Tools use docstrings to build help pages and to show hints in your editor.

main.pywhole filepython
"""Shopping total.

A docstring is a string written at the very top of a file."""

print(__doc__)

05PEP 8 in one picture

The two versions below do the same thing. The second follows PEP 8: spaces around operators, snake_case names, a constant in capitals. A formatter produces the second from the first automatically.

main.pywhole filepython
# hard to read
TotalPrice=basePrice*1.18+shippingCost

# PEP 8
total_price = base_price * 1.18 + shipping_cost
PEP 8 in one picturediagram
Rendering diagram…

06The Zen of Python

import this prints the Zen of Python by Tim Peters. import loads a module (Topic 6.1); this module is a small joke, because loading it prints the poem. The lines are a compass for choosing between two ways to write the same thing: when in doubt, pick the simpler and clearer.

Try it yourself

  1. 1

    Rename for clarity

    Take t = 0.18 and p = 200. Rename them to tax_rate and price, and rewrite the calculation. Is a comment still needed?

  2. 2

    Comment out a line

    In the first example, put # in front of the print line and run it. Nothing is printed, because the line became a comment.

  3. 3

    Read the Zen

    Run the second example and pick the three lines you like best. Write down, in your own words, what each means for the code you will write.

Code & diagrams

A commented program with a constant New tab

The last print shows that a # inside quotes is just text.

Sign in to run this example in your browser.

Expected output

Total with tax: 236.00
# this is inside a string, not a comment
A docstring and the Zen of Python New tab

import this prints the poem as soon as it is imported. The docstring is printed last.

Sign in to run this example in your browser.

Expected output

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Shopping total.

A docstring is a string written at the very top of a file.
Format and check from the terminalbash

Not runnable here. Ruff is a separate tool that you install on your computer (Topic 11.6). The commands are shown without output because the output depends on your code.

ruff format .
ruff check .

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Forget that # is only for one line

Write a note over two lines but put # only on the first.

main.pywhole filepython
# This note is long and
continues on the next line
print("hi")
terminal
$ python main.py
── what you'll see ──
File "main.py", line 2
continues on the next line
^^
SyntaxError: invalid syntax

Myth vs fact

Myth

More comments mean better code.

Fact

Comments that repeat the code add noise and go out of date. Clear names, short steps and a few comments that explain *why* are better than many comments on every line.

Myth

Constants in CAPITALS cannot be changed.

Fact

Python has no constants. The capital letters are only a promise to other programmers; the interpreter will let you reassign.

Myth

Style is a matter of taste, so PEP 8 does not matter.

Fact

Everyone in the Python world reads code with the same layout, so shared style saves time in every review. Formatters mean you don't have to think about it.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    A comment costs nothing at run time: the tokenizer drops it before parsing. A docstring is stored in the code object, so it costs a little memory, but you can read it with help() and tools. Python removes docstrings if you run with -OO.

  • ▸

    Python has no real constants. typing.Final (Python 3.8) marks a name as "do not reassign" for type checkers such as mypy and Pyright, but the interpreter does not enforce it. Special comments are read by tools, not by Python: # type: ignore, # noqa: E501 (Ruff and flake8), # fmt: off and the encoding line # -*- coding: utf-8 -*- (needed only for non-UTF-8 files, since UTF-8 is the default since Python 3). Conventions for docstrings are in PEP 257; PEP 8 asks for 72 characters in comments and docstrings, 79 in code, and Ruff and Black default to 88.

  • ▸

    Type hints (Phase 10) replace many comments such as # list of names. Annotated functions, docstrings and tests together do the work that comments alone cannot.

  • ▸

    Teams enforce style in CI with ruff check and ruff format --check so style never needs arguing in a code review (Topic 11.8). Ruff is a fast, single-tool replacement for the older flake8, isort and black combination.

  • ▸

    Comments that explain a hack, a workaround or a link to a bug report are the most valuable kind, because the code alone cannot tell the next engineer why the strange thing is there. Mark unfinished work with TODO: and a name, and review such comments regularly.

Remember this

  1. 1

    Write comments that say why, not what. # add 1 to count next to count += 1 only repeats the code. # the GST rate is fixed by law explains something the code cannot say. If you feel a comment is needed to explain *what* the code does, try renaming the variables first. A # inside a string is just a character ("# not a comment").

  2. 2

    A docstring is a string placed first in a file, function or class to describe it. (A function is a named group of steps, Phase 5. A class is a blueprint for your own kinds of value, Phase 8. A module is a .py file used as a toolbox, Phase 6.) A docstring at the top of a file is the module's description, and Python stores it in __doc__. In Phase 5 you will put docstrings inside functions, and tools such as help() and editors will show them. Docstrings use triple quotes. Comments are for people reading the source; docstrings are also available to the program while it runs.

  3. 3

    PEP 8 is the official Python style guide (PEP stands for Python Enhancement Proposal). The essentials: indent with 4 spaces; use snake_case for variables and functions; spaces around operators and after commas (total = price + tax); no spaces just inside brackets; two blank lines between top-level definitions (functions and classes that are not inside anything else); lines up to 79 characters (many teams allow 88 or 100). Style is not about taste: agreed rules mean everyone reads everyone's code without friction.

  4. 4

    Python code uses naming conventions to tell kinds of name apart. snake_case is for variables and functions. CamelCase (also called PascalCase) is for classes (Phase 8). ALL_CAPS is for constants: values that should never change while the program runs, such as GST_RATE = 0.18 or MAX_RETRIES = 3. Python does not stop you from changing a constant. The capitals are a promise between programmers.

  5. 5

    Do not memorise or fight over style. Use a formatter: ruff format (or the older black) rewrites your code to a standard layout, and ruff check finds common problems, such as an unused variable or a name that is never defined. Topic 11.6 sets it up. Editors can run it every time you save.

  6. 6

    Python has a built-in poem about its design, the Zen of Python. Type import this to read 19 short lines such as "Readability counts" and "Explicit is better than implicit". Read them again after Phase 5; they explain why Python code looks the way it does.

Explain it without notes

01

What makes a good comment, and what makes a bad one?

02

What is a docstring, and how is it different from a comment?

03

List four rules from PEP 8 and say why they matter.

04

What is the naming convention for variables, classes and constants in Python?

Practice

01

Rewrite this code in good style: r = 0.05, then m = 1000, then i = m * r, then print(i). Rename the variables so they say what they hold, make the rate a CAPITAL constant, and add two comments that explain why.

02

Write a program with a module docstring and print the docstring.

03

Rewrite A=5;B=A*2 in PEP 8 style on two lines with good names.

Trade-offs

  • ↔

    Comments vs. self-explaining code. Comments carry intent the code cannot, but every comment must be kept up to date. Prefer names and small steps; keep comments for reasons.

  • ↔

    Strict style vs. freedom. A formatter removes your choice of layout. What you gain is code that always looks the same, and no time lost in arguments about spaces.

Done when you can

  • Done when you can write a # comment on its own line and at the end of a line.

  • Done when you can explain why comments should say *why* instead of *what*.

  • Done when you can write a module docstring and print it.

  • Done when you can name variables, constants and classes in the right style.

  • Done when you can run import this and say what the Zen of Python is.