Python / Syntax / Comments
A Python comment starts at # outside a string and continues to the end of that line. To comment across multiple lines, prefix each line with #; triple quotes create a string literal rather than a dedicated comment syntax. A docstring at the start of a function or similar definition has a separate documentation role.
Single-line comments and # inside strings
Comments explain intentions and conditions; ordinary comment contents are ignored by Python’s syntax. They can occupy an entire line or follow code. See the official comment rules for the exact boundary.
The examples require only Python 3. Save each complete example as UTF-8 in comments_example.py and run python comments_example.py, or python3 where appropriate. Replace the file contents to run later examples independently.
# Calculate the total before discounts.
price = 100
quantity = 2 # Number of items
print(price * quantity)
Expected output:
200
A # within quotes is part of the string. Text containing it, including a URL fragment, is not cut off as a comment.
print("# This is part of a string")
print("https://example.com/page#section")
# This is part of a string
https://example.com/page#section
Prefix every line of a longer comment
Python has no separate block-comment syntax like C’s /* ... */. Write a longer explanation by commenting each line. Aligning it with the relevant code makes its scope easier to understand.
# The sample uses a fixed discount rate.
# Production rules may depend on the customer.
base_price = 100
discount_rate = 0.1
print(base_price * (1 - discount_rate))
90.0
To disable code temporarily, comment its lines and remove those comment markers to re-enable it. Editors’ multiple-line comment commands usually automate this operation. Keep older implementations in version-control history rather than accumulating permanently commented-out alternatives.
Triple-quoted text and docstrings are strings
Triple single or double quotes create a string literal that may span lines. A string placed as the first statement of a module, class, or function becomes its docstring, available through __doc__ and help tools. The official docstring explanation describes its purpose and position.
def greet(name):
"""Return a greeting for name."""
return f"Hello, {name}"
print(greet("Ada"))
print(greet.__doc__)
Hello, Ada
Return a greeting for name.
This value documents the function and is accessible, unlike ordinary explanatory comments. The same quoting form also stores actual data:
notes = """first line
second line"""
print(notes.splitlines())
['first line', 'second line']
Wrapping arbitrary code in triple quotes does not turn it into a true comment. Matching quotes inside the wrapped content can break the syntax, and its position may make it a docstring. Use # when you mean to disable code.
A block containing only comments needs a statement
Blocks introduced by def, if, and similar syntax require an actual statement. Comments do not count, so leaving only a comment can raise IndentationError. Use the no-operation pass statement as a placeholder.
source = "def todo():\n # Implement later\n"
try:
compile(source, "example", "exec")
except IndentationError:
print("IndentationError")
def todo():
# Implement later
pass
print(todo())
IndentationError
None
The first part compiles invalid code held in a string and catches its error so the example can continue. The later function is valid because it contains pass. With no explicit return statement, its call returns None.
Useful explanations and special directives
PEP means Python Enhancement Proposal. The comment guidance in PEP 8 warns about comments that contradict the code. Explain decisions, external constraints, and important conditions rather than restating obvious operations, and update comments when code changes. Ordinary inline comments conventionally have at least two spaces before # and one after it.
Some comments have meaning to tools or source-file processing. A valid encoding declaration on the first or second line can affect how the file is read; Python 3 defaults to UTF-8. Treat linter and type-checker directives separately from explanatory prose, and investigate warnings before hiding them broadly.




