Python Comments
Comments are lines that Python's interpreter completely ignores — they exist purely for humans. Writing good comments is a professional habit that makes code understandable weeks, months, and years later. This chapter covers every type of Python comment, when to use each one, and the best practices that separate clean codebases from messy ones.
What Are Comments?
A comment is any text in your Python file that the interpreter completely ignores when running the program. Comments produce no output, use no memory, and have zero effect on how your program behaves.
They exist entirely for humans — to explain what code does, why a decision was made, or to temporarily disable lines during debugging. Professional developers spend more time reading code than writing it, and good comments make that reading dramatically faster.
# add 1 to x before
x += 1 adds zero value. A useful comment is:
# offset by 1 — API returns 0-based page indices.
Single-line Comments — The # Symbol
A single-line comment starts with the hash # symbol. Python
ignores everything from # to the end of that line. This is the most common
comment type you'll use daily.
# This entire line is a comment — Python skips it
name = "Alice" # variable stores the user's name
age = 25 # must be an integer
# Step 1: Calculate the discounted price
original = 1000
discount = 0.10 # 10% promotional discount
price = original * (1 - discount)
print(price) # 900.0
# print("debug line — disabled for now")
print(f"Final price: {price}")
# and
1 space after it.
Ctrl + / (Windows/Linux) or
Cmd + / (macOS) to toggle comments on the selected
lines instantly.
# and your
comment text: # good comment. Avoid
#bad comment (no space) or
# too many spaces. For inline comments, use at least two
spaces before the hash: x = 5 # good.
Inline Comments
An inline comment appears on the same line as code, separated by at least two
spaces before the #. Use them sparingly — only when the code
isn't self-explanatory, particularly for "magic numbers" that would confuse a future reader.
# ✅ GOOD inline comments — explain non-obvious values
TIMEOUT = 30 # seconds before request gives up
MAX_RETRY = 3 # retry 3 times before marking as failed
TAX_RATE = 0.18 # India GST — 18%
CHUNK_SIZE = 1024 # bytes per network read
# ❌ BAD inline comments — just state the obvious
x = 5 # set x to 5 ← useless: code says it already
i += 1 # increment i by 1 ← useless
print(name) # print name ← useless
Multi-line Comments
Python has no dedicated multi-line comment syntax like
/* ... */ in C or Java. The correct Python approach is
consecutive lines each starting with #. This is what PEP 8
recommends.
"""...""" (triple-quoted strings) used as
multi-line comments in the middle of functions. This is technically a
string literal that Python evaluates and discards — it still uses memory for a moment
and can cause subtle issues. Reserve """...""" exclusively
for docstrings at the top of functions, classes and modules.
# ──────────────────────────────────────────────────────────
# File : order_processor.py
# Author: K2infocom Dev Team
# Date : 2025-01-15
# Desc : Handles all order lifecycle from cart to delivery.
# ──────────────────────────────────────────────────────────
# This function calculates the final price after discount.
# Business rule: discount is ALWAYS applied before tax.
# Ref: finance-policy-v3.pdf, section 4.2
def final_price(base, discount, tax):
after_discount = base * (1 - discount)
return round(after_discount * (1 + tax), 2)
# TODO : add currency conversion in v2.0
# FIXME: edge case when base is 0 causes divide-by-zero
# NOTE : tax_rate is always GST (18%) for Indian customers
result = final_price(1000, 0.10, 0.18)
print(result) # 1062.0
# TODO: add caching layer.
# FIXME: crashes when list is empty.
# NOTE: API changed in v3 — returns dict not list.
─ = ─ * ─) works — just stay consistent across the
project.
Docstrings — Python's Official Documentation
A docstring (documentation string) is a triple-quoted string placed as the
very first statement inside a function, class, or
module. Unlike ordinary comments, docstrings are
stored in memory as the __doc__ attribute
and are accessible at runtime via help() and IDE tooltips.
# ── 1. One-line docstring (simple, obvious functions) ─────────
def square(n):
"""Return the square of n."""
return n ** 2
print(square(4)) # 16
print(square.__doc__) # Return the square of n.
help(square) # shows formatted help in terminal
# ── 2. Multi-line docstring — Google style (most popular) ─────
def apply_discount(price, discount_pct):
"""
Return price after applying a percentage discount.
Args:
price (float): Original price — must be positive.
discount_pct (float): Discount as a percentage, e.g. 10 for 10%.
Returns:
float: Discounted price rounded to 2 decimal places.
Raises:
ValueError: If price is negative or discount_pct is outside 0-100.
Example:
>>> apply_discount(500, 10)
450.0
"""
if price < 0:
raise ValueError("price cannot be negative")
return round(price * (1 - discount_pct / 100), 2)
# ── 3. Class docstring ────────────────────────────────────────
class BankAccount:
"""
Represents a bank account with deposit and withdrawal operations.
Attributes:
owner (str): Account holder name.
balance (float): Current balance in INR.
"""
def __init__(self, owner, balance=0.0):
"""Initialise account with owner name and optional starting balance."""
self.owner = owner
self.balance = balance
def deposit(self, amount):
"""Add amount to balance. Amount must be greater than zero."""
self.balance += amount
:param:
syntax). Google style is the most readable and is recommended for new projects. Whatever you
choose, use it consistently across the entire codebase.
Comment Types at a Glance
Here is a concise comparison of all Python comment types so you always know which one to reach for:
| Type | Syntax | Stored at runtime? | Best used for |
|---|---|---|---|
| Single-line | # text |
✗ No — fully ignored | Explaining a line or block of code |
| Inline | code # text |
✗ No — fully ignored | Clarifying magic numbers or specific values |
| Multi-line |
# line 1
|
✗ No — fully ignored | File headers, long explanations, TODO/FIXME blocks |
| Docstring | """text""" |
✓ Yes — in .__doc__ | API documentation for functions, classes, modules |
Your everyday comment. Use before a block of code to describe what it does. Python skips it completely.
Only when a specific value needs clarification right next to it. Two spaces before
the #.
Multiple consecutive # lines. Used for file
headers, policy notes and TODO/FIXME markers.
First statement of a function/class/module. Stored in
__doc__. Readable by
help() and IDE tooltips.
Select lines → press Ctrl+/ to toggle comments.
Mac: Cmd+/. Works on single and multiple lines.
Call help(any_function) in the Python REPL to
instantly read its docstring in a formatted view.
Best Practices for Writing Comments
Bad comments are worse than no comments — they mislead readers and rot when code changes but comments don't. Here are the principles every professional Python developer follows:
# multiply by -1 adds nothing. Instead write
why:
# reverse sign — API returns inverted values for descending sort.
calculate_monthly_interest() needs no
explanation; calc() needs a novel. Good names
eliminate most of your commenting burden.
# TODO: add rate limiting before v2 launch.
"""Return total price with tax applied.""". This
enables help() and IDE autocomplete
descriptions.
Using Comments to Disable Code
During debugging you can temporarily prevent a line from running by adding
# in front — this is called
"commenting out". The original code stays intact and can be re-enabled
instantly by removing the hash.
# Testing: try with uppercase first, then toggle to see the difference
def process(text):
text = text.strip()
text = text.upper() # active
# text = text.lower() ← commented out: testing uppercase branch
return text
# Switching between old and new implementation:
# result = old_get_user(user_id) ← keep for fallback
result = new_get_user(user_id) # active: using new API
# Testing multiple input scenarios quickly:
sample = " hello world "
# sample = "" ← test empty string
# sample = None ← test None input
# sample = " spaces " ← test whitespace only
print(process(sample))
All comment types in one real-world example
# ─────────────────────────────────────────────────────
# Module : price_calculator.py
# Author : K2infocom
# Purpose: Price and discount utilities for checkout.
# ─────────────────────────────────────────────────────
GST_RATE = 0.18 # India GST — 18% flat rate
def apply_discount(price, discount_pct):
"""
Return price after applying a percentage discount.
Args:
price (float): Original price — must be > 0.
discount_pct (float): e.g. 10 means 10% off.
Returns:
float: Discounted price rounded to 2dp.
Example:
>>> apply_discount(1000, 10)
900.0
"""
# Convert % to a decimal multiplier
multiplier = 1 - (discount_pct / 100)
return round(price * multiplier, 2)
def add_tax(price):
"""Apply standard GST and return the final price."""
return round(price * (1 + GST_RATE), 2)
# ── Main execution ────────────────────────────────────
base = 1000
discount = 10 # 10% promotional offer
# TODO: read discount from database in v2.0
after_discount = apply_discount(base, discount)
final = add_tax(after_discount)
print(f"Base price : ₹{base}")
print(f"After {discount}% off : ₹{after_discount}")
print(f"After 18% GST: ₹{final}")
# Base price : ₹1000
# After 10% off : ₹900.0
# After 18% GST: ₹1062.0
- Comments are ignored by Python at runtime — they exist entirely for human readers to understand the code.
-
Single-line comments start with
#. Everything from#to end-of-line is skipped. Always add one space after the hash. -
Inline comments follow code on the same line. Use at least two spaces
before the
#. Use them only for magic numbers and non-obvious values. -
Python has no native multi-line comment syntax. Use consecutive
#lines — never misuse triple-quoted strings in the middle of code. -
Docstrings (
"""...""") are the first statement inside a function/class/module. They're stored in.__doc__and shown byhelp()and IDEs. - Use TODO / FIXME / NOTE markers to flag pending work and known issues — most editors highlight them automatically.
- Always comment the WHY, not the WHAT. Update comments when code changes — stale comments are worse than none.
-
Press
Ctrl + /in VS Code to toggle comments on selected lines. Never commit large blocks of commented-out code.
A comment (#) is completely
invisible to the Python interpreter — it is stripped before execution and leaves
no trace in memory. A docstring ("""...""") is a special string literal placed at
the start of a function, class, or
module. Python stores it in the object's
.__doc__ attribute at runtime, making it
accessible via help(function_name), IDE
tooltips, and documentation generators like Sphinx. The key difference: comments
are purely for source-code readers; docstrings are for both source-code readers
and tools that inspect the running program.
No — Python has no multi-line comment operator like
/* ... */ in C or Java. The correct approach
is consecutive lines each beginning with #.
Some developers misuse triple-quoted strings ("""...""") as multi-line comments inside
functions, but this is technically incorrect —
Python evaluates and briefly allocates memory for the string object before
discarding it. Reserve triple quotes exclusively for
docstrings at the top of functions, classes, and modules.
These are standard informal markers that most editors highlight automatically:
-
# TODO: — work that still needs to be done. Example:
# TODO: add caching before v2 release -
# FIXME: — a known bug or broken code. Example:
# FIXME: crashes when list is empty -
# NOTE: — important context a future reader must know.
Example:
# NOTE: API changed in v3, now returns a dict
They help teams track issues without switching to a separate task tool, and tools like VS Code's "TODO Highlight" extension can aggregate all of them across the project.
Commented-out code in a committed codebase causes several problems: it clutters
the file making it harder to read, it confuses teammates about whether the code
is still relevant or needed, it gets stale instantly — the surrounding code
changes but the commented block doesn't — and it signals poor version control
habits. The purpose of Git is precisely to preserve every historical version of
your code. If you ever need an old version, use
git log or
git diff to retrieve it. The rule: delete
the code locally for debugging, restore it if needed, and never send
commented-out blocks into the main branch.
A "magic number" is a bare numeric constant in code whose
meaning isn't obvious from context. For example,
TIMEOUT = 30 — without a comment, a reader
doesn't know if 30 is milliseconds, seconds, or minutes. Comments solve this:
TIMEOUT = 30 # seconds before the HTTP request gives up.
The best practice is to give it a named constant AND an inline comment if the
unit or reason still isn't clear:
MAX_RETRY = 3 # retry 3 times before marking the task failed.
This is one of the few cases where inline comments are genuinely valuable and
not considered noise.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.