Tutorials Python Comments
Ch 4 / 58
Python Beginner 4 min read Chapter 4 of 58

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 you'll learn in this chapter
What comments are and why they matter
Single-line comments with the # symbol
Inline comments — after code on the same line
Multi-line comments using consecutive #
Docstrings — Python's official documentation format
Best practices — what to comment and what to avoid
Advertisement

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.

The Golden Rule Comment the WHY, not the WHAT. The code already shows what it does. A comment like # add 1 to x before x += 1 adds zero value. A useful comment is: # offset by 1 — API returns 0-based page indices.
Invisible to Python
Interpreter skips them entirely at runtime
For Humans Only
Explain intent, context, and decisions
Debug Tool
Temporarily disable code without deleting
3 Types in Python
Single-line, multi-line, docstrings

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.

Python — single-line comments
# 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}")
# on its own line
The whole line is a comment — nothing executes. Use it to explain a block of code that follows, or to add a section heading inside a long file.
code # inline comment
Comment follows code on the same line. PEP 8 says use at least 2 spaces before the # and 1 space after it.
# disabled code
# prefix is also used to "comment out" code temporarily during debugging — that code won't run.
Shortcut: Ctrl + /
In VS Code, select lines and press Ctrl + / (Windows/Linux) or Cmd + / (macOS) to toggle comments on the selected lines instantly.
PEP 8 formatting Always put one space between the # 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.

Python — good and bad inline comments
# ✅ 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
Useful inline comment
result *= -1 # reverse sign — API returns # inverted values
Useless inline comment
result *= -1 # multiply result by -1

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.

Common misconception You may see """...""" (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.
Python — correct multi-line comment style
# ──────────────────────────────────────────────────────────
# 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:
Marks work that still needs to be done. VS Code and most IDEs highlight these automatically. Example: # TODO: add caching layer.
# FIXME:
Marks a known bug or broken behaviour. Example: # FIXME: crashes when list is empty.
# NOTE:
Adds important context a future reader must know. Example: # NOTE: API changed in v3 — returns dict not list.
# ─── Section ───
Visual divider lines help readers navigate long files. Any character (─ = ─ * ─) works — just stay consistent across the project.
Advertisement

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.

Python — docstrings for functions, classes and modules
# ── 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
Choose a docstring style and stick to it The three most common styles are Google (Args / Returns), NumPy (Parameters / Returns with dashes), and Sphinx (: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
# line 2
✗ No — fully ignored File headers, long explanations, TODO/FIXME blocks
Docstring """text""" ✓ Yes — in .__doc__ API documentation for functions, classes, modules
# Single-line
Most Common

Your everyday comment. Use before a block of code to describe what it does. Python skips it completely.

code # inline
Use Sparingly

Only when a specific value needs clarification right next to it. Two spaces before the #.

# Multi-line
For Long Notes

Multiple consecutive # lines. Used for file headers, policy notes and TODO/FIXME markers.

"""Docstring"""
API Docs

First statement of a function/class/module. Stored in __doc__. Readable by help() and IDE tooltips.

Ctrl + /
VS Code Tip

Select lines → press Ctrl+/ to toggle comments. Mac: Cmd+/. Works on single and multiple lines.

help(func)
Live Docs

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:

Explain WHY, not WHAT
The code already shows what it does. A comment like # multiply by -1 adds nothing. Instead write why: # reverse sign — API returns inverted values for descending sort.
Keep comments up to date
A comment that no longer matches the code is actively harmful — it misleads the reader. When you change code, update or remove its comment immediately. Stale comments are the leading source of confusion in large codebases.
Write self-documenting code first
The best comment is no comment at all. Use clear variable names — calculate_monthly_interest() needs no explanation; calc() needs a novel. Good names eliminate most of your commenting burden.
Use TODO / FIXME / NOTE markers
Standard markers let your team track issues without a separate task tool. Most editors highlight them automatically in different colours. Always include what needs to happen: # TODO: add rate limiting before v2 launch.
Never commit large commented-out code blocks
Commenting out code during debugging is fine. But don't commit it to version control — it clutters the codebase, confuses teammates, and becomes stale instantly. That's what Git history is for. Delete it before merging.
Docstring every public function and class
If a function is callable by anyone outside your immediate file, give it a docstring. Even one line is better than nothing: """Return total price with tax applied.""". This enables help() and IDE autocomplete descriptions.
Professional commenting
# Offset by 1: API uses 0-based pages # but our UI shows 1-based to users page_display = page_api + 1 GRACE_PERIOD = 7 # days before account locked
Useless commenting
# add 1 to page_api page_display = page_api + 1 # GRACE_PERIOD equals 7 GRACE_PERIOD = 7

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.

Python — commenting out code during debugging
# 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))
Don't commit commented-out code Commenting out code during local debugging is perfectly fine. But never commit large blocks of commented-out code to version control. It creates confusion about whether code is still relevant, clogs pull request reviews, and eventually becomes completely misleading. Delete it — Git history preserves the old version if you ever need it back.

All comment types in one real-world example

Python — price_calculator.py (complete 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
Chapter Summary
  • 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 by help() 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.
⚡
Free Resource
Download our Python Cheat Sheet
Comments, syntax, variables, loops, functions — all on one printable A4 page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

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.

✓ Answer

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.

✓ Answer

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.

✓ Answer

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.

✓ Answer

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.

MCQ 1 of 3
Which of the following correctly creates a single-line comment in Python?
MCQ 2 of 3
Where must a docstring be placed to be recognised by Python as a docstring?
MCQ 3 of 3
What is the keyboard shortcut in VS Code to toggle a comment on selected lines?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel