Comments: Write Code Humans Can Read
Introduction
In this chapter, you will learn how to use comments in Python to make code easier to understand and maintain. Comments do not affect program execution, but they are essential for communication between developers. Good comments help future you and your teammates understand intent quickly.
Prerequisites
- Python
3.10+installed - Basic understanding of variables, loops, functions, and mini scripts
- Ability to run
.pyfiles in terminal or IDE
What Is a Comment
A comment is text in code that Python ignores when running the program.
You write comments for humans, not for the interpreter.
1) Single-Line Comments
Use # for single-line comments.
# Store user name
user_name = "Alice"
# Print welcome message
print(f"Welcome, {user_name}!")This is the most common comment style in daily coding.
2) Inline Comments (Use Sparingly)
Inline comments are placed on the same line as code.
score = 95 # Final exam scoreUse inline comments only when they add quick context.
Avoid noisy comments that repeat obvious code.
Tip
Best Practice
Comment the "why", not the obvious "what".
If code says total = price * quantity, do not comment "multiply price and quantity" unless extra business context is needed.
3) Multi-Line Explanations
For longer notes, use multiple # lines.
# Business rule:
# - VIP users get 20% discount
# - New users get 10% discount
# - Others get no discount
if is_vip:
discount = 0.2
elif is_new_user:
discount = 0.1
else:
discount = 04) Docstrings vs Comments
Docstrings describe modules, functions, and classes, and can be accessed programmatically.
def calculate_total(price, quantity):
"""Return total payment before discount."""
return price * quantityDifference:
- Comment: free-form explanation for readers
- Docstring: structured documentation for APIs/modules/functions/classes
5) Real Mini Example: Guess Validation Script
This mini example shows practical comments in a small flow.
# Set secret number for guessing
secret_number = 18
# Track total attempts
attempt_count = 0
# Repeat until user guesses correctly
while True:
# Read user guess as integer
guess = int(input("Guess the number: "))
attempt_count += 1
# Compare guess with secret number
if guess < secret_number:
print("Too low.")
elif guess > secret_number:
print("Too high.")
else:
# End loop when guess is correct
print(f"Correct! Attempts used: {attempt_count}")
breakThis style keeps complex logic clear without over-commenting every line.
6) Comment Style Guidelines
Use these practical rules:
- Keep comments short and specific
- Update comments when code changes
- Use consistent tense and wording
- Prefer clear code first, comments second
- Remove outdated comments immediately
Warning
Outdated comments are worse than no comments.
If comment and code disagree, readers lose trust in both.
Common Beginner Mistakes
Mistake 1: Commenting Every Line
Too many comments create visual noise and reduce readability.
Mistake 2: Writing Vague Comments
Comments like "do something here" are not helpful.
Mistake 3: Leaving Dead or Misleading Comments
After refactoring, old comments may become incorrect and should be removed.
Surprise Practice Challenge
Take your previous ranking game or guess game script and improve it:
- Add comments for key blocks only
- Add one clear docstring to a helper function
- Remove any redundant comments
- Ask yourself: "Can a beginner understand this in 30 seconds?"
If yes, you are already writing maintainable code, not just runnable code.
FAQ
Do comments affect performance?
No. Python ignores comments during execution.
Should I write comments in every function?
Not always. Write comments when intent is not obvious. For reusable functions, prefer clear names plus docstrings.
Can comments replace good variable names?
No. Clear naming is the first layer of readability; comments are support, not a substitute.
What language should comments use?
Use one consistent language across the project. In team settings, English is usually preferred for broader collaboration.