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().
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. |
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
An inline comment shares the same physical line as an executable Python statement. PEP 8 specifies two mandatory formatting rules:
# 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
Unlike languages with /* ... */ block syntax, Python does not have a formal multiline comment delimiter. There are two standard approaches:
# and a space.''' 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.
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 |
Python tools and Unix shells inspect special comment directives:
#!/usr/bin/env python3): Instructs Unix kernels to execute the file with Python 3.# -*- coding: utf-8 -*-): Specifies source encoding (PEP 263).# type: int.# 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
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
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
x = 0 # set x to 0).Watch our step-by-step video tutorial demonstrating single-line, inline, and multiline comments in Python:
Practice writing clean single-line comments, PEP 8 inline comments, docstrings, and linter directives in our interactive companion Jupyter Notebook:
Explore interactive code cells, inspect __doc__ metadata, test linter pragma directives, and run self-validating assertions.
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!
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.
No. Comments are stripped during tokenization. They produce zero bytecode instructions and have no impact on execution speed or memory usage.
No, comments written with # cannot be accessed programmatically. To create runtime-accessible documentation, use docstrings accessible via obj.__doc__.
# 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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.