002. Comments
Document intent, not mechanics
002. Comments
Aryan writes a RAM alert function. It fires a warning if memory usage exceeds a threshold.
def check_ram(used_mb, total_mb):
usage = used_mb / total_mb
if usage > 0.85:
return "WARN"
return "OK"Three weeks later, his teammate asks: “Why 0.85? Is that from a spec? A guess? A Stack Overflow answer?”
Without a comment, no one knows. And next month, someone will “fix” 0.85 to 0.9 because it seems more round — and the production alert will start missing real memory pressure.
Comments exist to anchor the WHY behind a decision so the number can never be changed silently. Fix the late-fee function below using the same principle: add comments explaining the rate and the cap, and correct the wrong cap value.
💡 Fun fact: The # comment style traces back to shell scripting in the 1970s. Python adopted it from Unix shells — Guido wanted the language to feel natural to system programmers who already used # for inline notes.
⚠️ Watch out: The most common beginner mistake is writing what the code does rather than why. A comment like # multiply by 0.25 is useless — the code already shows that. The valuable comment is # 25 cents per day per library policy.
🤔 Think about it: If a comment just restates the code in plain English, does it actually help the next reader — or does it create two things that can drift out of sync?
Learning objectives
- Write single-line comments with
- Explain business logic and non-obvious decisions in comments
- Distinguish between useful and redundant comments
Key concepts
- comments
- documentation
- readability
Try it
Concept detail
Comments exist for humans, not for Python. The interpreter skips them entirely. The rule professionals follow: comment the WHY, not the WHAT.
‘fee = days_overdue * 0.25 # multiply by 0.25’ is a useless comment — the code already shows the multiplication. But ‘# 25 cents per day per library policy’ tells the reader WHERE the number comes from, so no one changes it in ignorance.
The broken code also has a real bug: the cap is 5.0 instead of 10.0. Both problems — the missing comment and the wrong value — are symptoms of the same root cause: undocumented business rules become invisible and get corrupted over time.
Well-placed comments prevent future readers (including yourself in 6 months) from quietly breaking rules they never knew existed.
Solution
def calculate_late_fee(days_overdue):
# 25 cents per day overdue
fee = days_overdue * 0.25
# Maximum fee capped at $10.00 to keep it fair
if fee > 10.0:
fee = 10.0
return feeTests
def test_normal_fee():
assert calculate_late_fee(4) == 1.0
def test_fee_capped_at_ten():
assert calculate_late_fee(60) == 10.0
def test_exactly_at_cap():
assert calculate_late_fee(40) == 10.0
def test_just_under_cap():
result = calculate_late_fee(39)
assert abs(result - 9.75) < 0.001