livepython.net
CHAPTER 06Comments
6.2  GOOD COMMENTS

How to Write Good Comments in Python

Explain Why, Not What

The best comments explain why the code does something. The code itself already shows what it does.

PYTHONedit me
price = 100

# Bad: repeats the code
total = price * 1.18  # multiply price by 1.18

# Good: explains the reason
total = price * 1.18  # add 18 per cent GST
print(total)
OUTPUT
118.0

"Multiply price by 1.18" tells the reader nothing new: they can see the * 1.18. "Add 18 per cent GST" tells them why 1.18, which they couldn't guess.

Think of a recipe note. "Add salt" is already in the recipe. "Add the salt last, or the dough won't rise" is the note worth writing.

Questions a good comment answers

  • Why this number? (# 60 seconds in a minute)
  • Why this order? (# load the prices before the discount)
  • What's surprising here? (# Python rounds 2.5 down to 2)
  • What must not change? (# the tests expect exactly two decimals)

When the "what" is hard

Sometimes a line really is hard to follow. Then a short "what" comment helps. But first, ask yourself: could clearer code, or a better variable name, make the comment unnecessary? You'll see how in the last lesson of this topic.

Code shows what happens. A good comment explains why.

your turnPick the right idea

Which comment is most helpful?

total = minutes / 60
Think about it, then pick one.

Don't Comment the Obvious

More comments aren't always better. A comment on every line makes code harder to read, not easier:

PYTHONedit me
# set name to Sunny
name = "Sunny"
# print the name
print(name)
# set age to 25
age = 25
# print the age
print(age)
OUTPUT
Sunny
25

Every comment here just repeats the line below it. The reader has to read everything twice, and learns nothing new.

Here's the same program, written well:

PYTHONedit me
name = "Sunny"
age = 25
print(name)
print(age)
OUTPUT
Sunny
25

It needs no comments at all: the names and the code say it all.

A simple test

Before writing a comment, ask: "Would a reader who knows a little Python understand this line without my comment?" If yes, skip the comment.

But: comments while you learn

While you're learning, it's fine to write comments that explain Python to yourself, like # // drops the decimals. They help you remember. Just know that in "real" code, other programmers already know these things, so they leave such comments out.

Think of road signs: a sign at every metre would be noise. Signs only at the tricky turns are the ones drivers actually read.

Comment the tricky parts, not every line.

your turnPick the right idea

Which line needs a comment the most?

Think about it, then pick one.
your turnOrder the lines

Put the lines in order: comment first, then the code it explains

  1. weeks = 3
  2. days = 7
  3. print(days * weeks)
  4. # 7 days in a week
These lines are mixed up. Put them back in order, then press Check.

Keep Comments Up to Date

A comment that's wrong is worse than no comment at all. Look at this:

PYTHONedit me
discount = 0.2  # 10 per cent discount
price = 1000
print(price - price * discount)
OUTPUT
800.0

The comment says 10 per cent, but the code uses 0.2, which is 20 per cent. Someone changed the number and forgot the comment. Now a reader doesn't know which one to trust, and might "fix" the code back to the wrong value.

Think of a signpost that points the wrong way. Without it, you'd ask for directions. With it, you confidently go the wrong way.

The rule

When you change code, check the comments around it. Update them in the same step, or delete them if they're no longer true.

Comments that go stale fast

  • Exact numbers: # loops 3 times (what if it becomes 4?)
  • Names of things: # uses the old_price variable (what if it's renamed?)
  • Promises: # this never happens (are you sure?)

The fewer details a comment repeats from the code, the less likely it goes wrong. "Add the student discount" stays true even if the discount changes. "Take off 10 per cent" doesn't.

TODO comments

Programmers mark unfinished work with # TODO:

PYTHONedit me
price = 100
# TODO: add delivery charges
print(price)
OUTPUT
100

Many editors list all the TODOs in a project, so nothing gets forgotten. Delete each one when the work is done.

When you change the code, update its comments too.

your turnPick the right idea

Which line's comment is wrong?

hours = 2 # 2 hours minutes = hours * 60 # 60 minutes in an hour seconds = minutes * 100 # 60 seconds in a minute
Think about it, then pick one.

Good Names Need Fewer Comments

Often the best fix for a confusing line is not a comment, but a better name. Compare:

PYTHONedit me
# a is the price, b is the number of items
a = 40
b = 3
print(a * b)  # total cost
OUTPUT
120
PYTHONedit me
price = 40
item_count = 3
total_cost = price * item_count
print(total_cost)
OUTPUT
120

Both print 120. The second one needs no comments at all, because the names already say what each value is. You learned this in chapter 4: good names say what they store.

Think of labels on jars in a kitchen. With clear labels, you don't need a separate list explaining what's in jar A and jar B.

Name the magic numbers

A number that appears in the code without explanation is called a magic number. Give it a name:

PYTHONedit me
tax_rate = 0.18  # GST
price = 200
print(price * tax_rate)
OUTPUT
36.0

Now 0.18 has a name, and the name explains it. If the tax changes, you change one line.

Comments and names work together

  • Names explain what a value is.
  • Comments explain why the code does something, or anything surprising.

Use names first. Add a comment when a name alone can't tell the whole story.

A clear name is a comment that can never go out of date.

your turnPick the right idea

Which version needs no comment?

Think about it, then pick one.
your turnPredict the output

What will this print?

item = "pen" price = 10 print(f"One {item} costs {price}")
Your turn! What will this code show on the screen?

Practice: Good comments

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 46.Python Program to Calculate a Bill with Clear CommentsEasySolve
  2. 47.Python Program to Explain a Calculation with CommentsMediumSolve