Comments & Docstrings
Code tells the computer what to do. Comments tell humans why. Both matter — and the difference between them confuses beginners constantly, so let's settle it in one lesson.
Comments: the # symbol
Anything after a # is ignored by Python completely — it exists only for human eyes:
# Calculate the final price with 18% tax
price = 100
final = price * 1.18 # multiply, don't add — tax applies to the base
print(final) # 118.0Three legitimate uses:
price = price * 1.18 already says *what* happens; the comment explains *why* 1.18 (tax rate). Code says what; comments say why.# TODO: handle empty cart marks work you know is pending.# in front of a line to switch it off without deleting:# print("debug: price is", price) # switched off, not deletedThis is called "commenting out" and you'll use it constantly while debugging.
The anti-pattern: commenting the obvious
# increment count by 1 ← the code already says this!
count = count + 1Bad comments repeat the code. Good comments explain the *reasoning the code can't express*:
# API rate-limits us to 1 request per second; sleep avoids the 429 error
time.sleep(1)Rule: if you remove the comment and nothing is lost, it was a bad comment.
Docstrings: documentation that Python reads
A docstring is a triple-quoted string placed first inside a function or file. Unlike comments, Python *keeps* docstrings and can display them:
def calculate_bmi(weight, height):
"""Return the BMI from weight (kg) and height (meters)."""
return weight / (height ** 2)The magic: Python can show you this documentation on demand:
help(calculate_bmi)Output:
Help on function calculate_bmi:
calculate_bmi(weight, height)
Return the BMI from weight (kg) and height (meters).Every professional Python function has a docstring — it's how libraries document themselves. When you ran help(len) and got real documentation, you were reading a docstring written by Python's developers.
Comment vs docstring — the one-line difference
Comment # | Docstring """...""" | |
|---|---|---|
| Read by | Humans only | Humans and Python |
| Location | Anywhere | First line inside functions/classes/files |
| Purpose | Explain reasoning | Document usage (feeds help()) |
Common Errors & Fixes
""" but not closed with """. They come in threes, both sides.# that wrapped from the previous line; every line needs its own #.✅ Checkpoint
help() — a comment or a docstring? *(Docstring)*# set x to 5 above x = 5. *(Delete it — it repeats the code. If there was a reason, state the reason.)*Next: indentation — the one Python rule that surprises every newcomer, explained so it never surprises you again.