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.
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)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.