BasicsChapter 4 of 114
Comments
Notes to humans that the interpreter skips, and how to use them well.
The hash mark
Everything after a # on a line is ignored by Python. It is there for whoever reads the code next, which is often you in three months.
# Work out the total including tax
price = 40
total = price * 1.2 # 20% VAT
print(total)Output
48.0
Commenting out code
Because Python ignores the rest of the line, a # is also how you switch a line off without deleting it:
print("this runs")
# print("this does not")
print("this runs too")Output
this runs this runs too
Most editors toggle this on a whole selection with Ctrl+/ or Cmd+/.
There is no block comment
Python has no /* ... */. To comment out ten lines you put a # in front of each one, and your editor does it for you.
You will sometimes see a triple-quoted string used for the job:
"""
This is a string that nobody uses.
Python builds it, then throws it away.
"""
print("done")Output
done
That works, but it is a string being evaluated and discarded rather than a comment. It is fine at the top of a file and a bad habit in the middle of a function.
Docstrings
A string on the first line of a function, class or file is a docstring. Python keeps it, and tools read it:
def area(width, height):
"""Return the area of a rectangle."""
return width * height
print(area(3, 4))
print(area.__doc__)Output
12 Return the area of a rectangle.
That is the difference worth remembering: a comment is thrown away, a docstring is part of the object and help() can find it.
Write comments that earn their place
A comment repeating what the code already says is noise, and it goes stale:
# add one to count
count = 0
count = count + 1
print(count)Output
1
The useful comment explains why, not what:
# The API rejects more than 50 ids per call, so send them in batches
batch_size = 50
print(batch_size)Output
50
Test yourself
2 questionsWhat is the difference between a comment and a docstring?
Show the answer
A comment is discarded; a docstring stays on the object and help() can read it — That is why __doc__ shows a docstring but can never show a comment.
Which comment is worth writing?
Show the answer
One explaining why a line exists — The code already says what it does. Why it does it is the part that is not recoverable from reading it.
Variables
Names that point at values, and what assignment really does.