Python Comments: Single-Line, Inline & Multiline Best Practices

Python Comments

In Python, comments are non-executable text annotations written with the hash symbol (#) to explain program logic, algorithmic constraints, and design rationale.

Zero Runtime Overhead: Python's lexical tokenizer strips comments during bytecode compilation, consuming zero runtime memory or execution time. While comments are discarded during parsing, runtime documentation is preserved separately through docstrings accessible via functions, classes, and help(). To track program state, explore variables and print().

1. Syntax & Foundations of Python Comments 🔝

Python designates the hash character # as the comment indicator. Any character following # on the same line is ignored by the Python interpreter:

Comment Type Syntax Pattern PEP 8 Rule Primary Use Case
Single-Line # Comment text Indent matching code block Block explanations preceding statements or functions.
Inline code # Comment text At least 2 spaces before # Brief clarifications on the same line as an assignment.
Multiline Block Consecutive # lines 1 space after each # Extended multi-sentence explanations and algorithm notes.
Docstring """Summary.""" PEP 257 docstring standard API documentation stored in __doc__ for runtime inspection.

2. Single-Line and Block Comments 🔝

A single-line comment begins with a # and a single space. When explaining multi-step workflows, place block comments directly above the code they describe, matching the code's indentation level:

# 1. Single-line and block comments
# Calculate net price after discount
subtotal = 120.0
discount_rate = 0.15  # 15% promotional discount
tax_rate = 0.08       # 8% state sales tax

# Compute final balance due
discount_amt = subtotal * discount_rate
taxable_amt = subtotal - discount_amt
total = taxable_amt * (1 + tax_rate)

print(f"Final Total: USD {total:.2f}")

Terminal Output:

Final Total: USD 110.16

3. Inline Comments & PEP 8 Formatting Rules 🔝

An inline comment shares the same physical line as an executable Python statement. PEP 8 specifies two mandatory formatting rules:

  • Separate the comment from the statement with at least two spaces.
  • Begin the comment with # and a single space before the text.
# 2. PEP 8 inline comment spacing
radius = 5.0  # Measured in centimeters (2 leading spaces before #)
area = 3.14159 * (radius ** 2)  # Circular base area formula

print("Computed Area:", area)

Terminal Output:

Computed Area: 78.53975

4. Multiline Comments: Multiple Hashes vs. Triple Quotes 🔝

Unlike languages with /* ... */ block syntax, Python does not have a formal multiline comment delimiter. There are two standard approaches:

  1. Consecutive Single-Line Comments (PEP 8 Recommended): Prepend each line with # and a space.
  2. Unassigned Triple-Quoted String Literals (''' or """): Evaluated as standalone expressions and discarded by the optimizer when unassigned.
# 3. Multiline comments: multiple # lines vs triple quotes
# PEP 8 standard approach for multiline blocks:
# Each line starts with a hash followed by a single space.
# This avoids allocating unassigned string literal constants.

user_status = "active"
print("User status:", user_status)

# Informal multiline block using triple-quoted string
"""
This multiline string is parsed by the Python compiler.
Because it is unbound, the peephole optimizer discards it.
"""
print("Program completed successfully.")

Terminal Output:

User status: active
Program completed successfully.

5. Docstrings vs. Comments: Runtime Metadata via __doc__ 🔝

While comments are stripped during compilation, docstrings are retained as runtime metadata. Placed as the first statement in a function, class, or module, Python stores the string in the __doc__ attribute:

# 4. Docstrings vs. Comments: inspection via __doc__
def calculate_circle_area(radius: float) -> float:
    """Calculates and returns the area of a circle given its radius.
    
    Arguments:
        radius (float): The radius in centimeters.
        
    Returns:
        float: Total circular area in square centimeters.
    """
    # Standard formula: pi * r^2 (internal note stripped in bytecode)
    return 3.141592653589793 * (radius ** 2)

print("Area of r=3:", calculate_circle_area(3.0))
print("\nRetrieved __doc__ metadata:")
print(calculate_circle_area.__doc__)

Terminal Output:

Area of r=3: 28.274333882308138

Retrieved __doc__ metadata:
Calculates and returns the area of a circle given its radius.
    
    Arguments:
        radius (float): The radius in centimeters.
        
    Returns:
        float: Total circular area in square centimeters.
Feature Code Comments (#) Docstrings ("""...""")
Runtime Availability Discarded during compilation (None) Retained in obj.__doc__ attribute
Help System Ignored by help() Rendered interactively in help(obj)
Target Audience Internal maintainers reading source code Callers using the public API interface

6. Special Comment Directives & Pragmas 🔝

Python tools and Unix shells inspect special comment directives:

  • Shebang (#!/usr/bin/env python3): Instructs Unix kernels to execute the file with Python 3.
  • Encoding Declaration (# -*- coding: utf-8 -*-): Specifies source encoding (PEP 263).
  • Type Comments (PEP 484): Legacy type hints like # type: int.
  • Linter Suppression: Flags like # noqa (Flake8/Ruff) and # type: ignore (mypy) bypass rule checks.
# 5. Special comment directives and pragma tags
# -*- coding: utf-8 -*-
# Specifies source file encoding (PEP 263)

# Legacy PEP 484 type hint comment
x = 100  # type: int

# Suppress linter line length warning (Flake8 / Ruff)
url = "https://www.plus2net.com/python/comments.php?tracking_id=alpha_ref"  # noqa: E501

# Suppress type checker mismatch (mypy)
raw_val = "42"
num = int(raw_val)  # type: ignore[assignment]

print("Parsed number:", num)

Terminal Output:

Parsed number: 42

7. Bytecode Inspection & Performance Verification 🔝

Do comments slow down Python scripts? No. Disassembling compiled bytecode with the standard dis module verifies that comments produce zero bytecode opcodes:

# 6. Bytecode inspection: comments leave zero trace in bytecode
import dis

def demonstration():
    # This comment is completely stripped during compilation
    value = 42  # Another stripped note
    return value

print("Disassembled instructions for demonstration():")
dis.dis(demonstration)

Terminal Output:

Disassembled instructions for demonstration():
  5           0 LOAD_CONST               1 (42)
              2 STORE_FAST               0 (value)

  6           4 LOAD_FAST                0 (value)
              6 RETURN_VALUE

8. Clean Code Best Practices: Explaining WHY vs. WHAT 🔝

Professional code documents what is happening; comments explain why it is happening:

# 7. Clean Code: Explaining WHY vs. Stating WHAT
# BEST PRACTICE: Explaining WHY a non-obvious business rule exists
def apply_shipping_fee(cart_weight_kg: float) -> float:
    # Carriers surcharge packages exceeding 20 kg due to freight tariffs
    if cart_weight_kg > 20.0:
        return 45.0
    return 15.0

print("Shipping for 25 kg: USD", apply_shipping_fee(25.0))

Terminal Output:

Shipping for 25 kg: USD 45.0
Best Practices
  • Explain Rationale: Document business rules, edge cases, and algorithmic constraints.
  • Keep Comments Updated: Synchronize comments with code edits. A stale comment is misleading.
  • Write Self-Documenting Code: Use clear variable and function names.
Anti-Patterns to Avoid
  • Stating the Obvious: Avoid comments that simply restate syntax (e.g. x = 0 # set x to 0).
  • Leaving Zombie Code: Avoid leaving blocks of dead commented-out code. Use Git version control.

9. Video Tutorial: Python Comments in Action 🔝

Watch our step-by-step video tutorial demonstrating single-line, inline, and multiline comments in Python:

Single line , inline and multiline Comments in Python for easy maintenance and understanding script

10. Interactive Notebook & Practice Exercises 🔝

Practice writing clean single-line comments, PEP 8 inline comments, docstrings, and linter directives in our interactive companion Jupyter Notebook:

Interactive Companion Jupyter Notebook

Explore interactive code cells, inspect __doc__ metadata, test linter pragma directives, and run self-validating assertions.

View on GitHub Run in Google Colab

Self-Verifying Assertion Suite

Run these unit checks directly in Python or your local environment to verify comment and docstring mechanics:

# 8. Self-verifying unit test suite for comments & docstrings
# Test 1: Comments are ignored and do not alter variable values
val = 10 # + 50 (ignored)
assert val == 10

# Test 2: Function __doc__ is preserved as runtime metadata
def sample_fn():
    """Sample docstring text."""
    # internal comment
    return True

assert sample_fn.__doc__ == "Sample docstring text."
assert sample_fn() is True

# Test 3: Unassigned strings do not define variable bindings
"""Unbound literal comment"""
assert 'literal comment' not in globals()

print("All Python comments & docstring unit assertions successfully verified!")

Terminal Output:

All Python comments & docstring unit assertions successfully verified!

11. Frequently Asked Questions (FAQ) 🔝

Does Python have a multiline comment tag like /* */?

No. Python does not have a dedicated multiline delimiter. The official PEP 8 standard is to use multiple consecutive lines starting with #. Unassigned triple-quoted strings ("""...""") are often used informally.

Do comments affect runtime performance?

No. Comments are stripped during tokenization. They produce zero bytecode instructions and have no impact on execution speed or memory usage.

Can comments be accessed at runtime?

No, comments written with # cannot be accessed programmatically. To create runtime-accessible documentation, use docstrings accessible via obj.__doc__.

What is the difference between # and # noqa?

# begins a regular human-readable comment. # noqa is a special pragma directive instructing linters (like Flake8 and Ruff) not to report style or formatting warnings for that line.

Further Reading & Related Tutorials 🔝




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer