PythonIntroduction to PythonPython fundamentals
What are comments in Python, and how do you write them?
Question 19 of 20 · Updated
On this page
- 1. How do you write a single-line comment in Python?
- 2. What is an inline comment?
- 3. How do you write multiline comments in Python?
- 4. Is a hash character always a comment?
- 5. Are triple-quoted strings multiline comments?
- 6. Comments vs docstrings
- 7. How does Python process comments internally?
- 8. Special comments and tool directives
- 9. What makes a good Python comment?
- 10. Can a comment replace an executable statement?
- 11. Common mistakes when writing comments
- Mistaking triple quotes for comment delimiters
- Writing comments that repeat the code
- Leaving stale comments after changing the implementation
- Keeping large blocks of obsolete code commented out
- Putting credentials or private information in comments
- Ignoring special comment directives during source transformations
- 12. Python comment best practices
- 13. Frequently asked questions
- Do comments slow down Python programs?
- Can Python comments appear inside an expression?
- Can I use // for Python comments?
- Can I comment out multiple lines at once?
- Are comments visible to the running program?
- 14. Interview-ready answer
- Key takeaways
- Official references
A comment in Python is explanatory text in source code that starts with a hash character (#) outside a string literal and continues to the end of the physical line. Comments help developers understand code without adding executable Python statements.
For example:
PYTHON# Calculate the number of items in the order. quantity = 3 print(quantity * 2)
Output:
6The first line is a comment. The interpreter executes the assignment and print call, not the explanatory text.
Comments are especially useful when explaining business rules, assumptions, limitations and reasons behind implementation decisions. They complement meaningful names, tests and documentation.
1. How do you write a single-line comment in Python?#
Place a hash character before the explanatory text. A standalone comment can appear above the statement or block it describes.
PYTHON# Calculate the number of items in the order. quantity = 3 print(quantity * 2)
The comment may contain ordinary sentences or even Python-like text; it is not interpreted as an executable statement.
Prefer a space after the hash character in ordinary explanatory comments. Indent a standalone comment consistently with the surrounding code.
2. What is an inline comment?#
An inline comment appears on the same physical line as executable code.
PYTHONtimeout_seconds = 5 # Upper bound for a single attempt. print(timeout_seconds)
Output:
5Python executes the assignment and ignores the explanatory portion as an ordinary comment. PEP 8 recommends at least two spaces between a statement and its inline comment, followed by a space after the hash character.
Inline comments are most helpful when they explain a non-obvious value, constraint or assumption. Avoid repeating information already obvious from a meaningful name. For example, a comment merely saying that timeout_seconds is a timeout adds little value.
3. How do you write multiline comments in Python?#
Python does not have a dedicated block-comment delimiter like the slash-asterisk syntax used by some other languages. To comment several lines, begin each line with a hash character.
PYTHON# Free delivery applies to orders of at least 500. # Orders below that threshold pay a flat delivery fee. order_total = 450 shipping = 0 if order_total >= 500 else 40 print(shipping)
Output:
40A paragraph of related comments is commonly called a block comment. Many editors offer a toggle-comment action that inserts or removes hash prefixes across selected lines.
Do not remove indentation from surrounding executable code while commenting a block. Python uses indentation to express program structure.
4. Is a hash character always a comment?#
No. A hash character inside a string literal is part of the string's contents.
PYTHONmessage = "Order #42" print(message) # The hash inside the string is data.
Output:
Order #42The hash inside the quoted string belongs to the order reference. The hash after the print call begins an inline comment.
This distinction is important for source-code analysis. Simply splitting a line at its first hash character is not a reliable way to remove comments, because doing so may damage strings and produce invalid or altered code.
5. Are triple-quoted strings multiline comments?#
No. Triple single quotes and triple double quotes create string literals. A standalone string expression is not a comment, even if it is written across multiple lines.
If a string literal is the first statement in a module, class or function body, it can serve as a docstring. Python exposes conventional docstrings through the corresponding object's __doc__ attribute.
PYTHONdef describe(): """Return a short status message.""" return "ready" print(describe()) print(describe.__doc__)
Output:
ready
Return a short status message.The docstring describes the function. It is not equivalent to a hash-prefixed comment.
A standalone string literal in another position is an expression statement. Its result may be unused, and CPython may optimise away some constant expressions, but that does not make the expression a lexical comment. Triple-quoted strings can also be assigned to variables, passed to functions and used as genuine multiline data.
Use hash-prefixed lines when you intend to write comments. Use docstrings when documenting a module, class, function or method interface.
6. Comments vs docstrings#
| Feature | Comment | Docstring |
|---|---|---|
| Syntax | Hash followed by text | String literal in a designated documentation position |
| Main purpose | Explain implementation details and decisions | Document the purpose or interface of a named construct |
| Runtime access | Not normally exposed as an object's documentation | Usually available via __doc__ and help() |
| Source-code treatment | Recognised lexically as a comment | Parsed as a string expression |
| Common style guidance | PEP 8 | PEP 257, alongside PEP 8 |
For public APIs, a docstring may describe parameters, return values, side effects and raised exceptions. A comment within the implementation may explain why a particular algorithm or validation condition is required.
Neither mechanism automatically ensures that documentation is correct or up to date.
CPython's -OO optimisation option removes docstrings, so applications should not rely on docstrings for essential runtime business logic. Ordinary source comments are still useful to development tools that inspect the original source text.
7. How does Python process comments internally?#
During lexical analysis, Python distinguishes comments from other source elements such as names, operators, numbers and strings. Ordinary comments are not executable statements and do not become normal operations in the program's compiled code.
However, tools that operate on source text can still inspect them. The standard-library tokenize module exposes comment tokens.
PYTHONimport io import tokenize source = 'print("# data") # explanation\n' for token in tokenize.generate_tokens(io.StringIO(source).readline): if token.type == tokenize.COMMENT: print(token.string)
Output:
# explanationThe tokenizer correctly distinguishes the hash inside the string from the actual comment. Token-based analysis is preferable to naive string splitting when working with valid Python source.
The abstract syntax tree normally excludes ordinary comments:
PYTHONimport ast source = "x = 1 # assign a value\n" print(ast.dump(ast.parse(source)) == ast.dump(ast.parse("x = 1\n")))
Output:
TrueThese two simple programs have the same default abstract syntax tree structure. The example does not imply that all comments can be stripped without consequence for every tool or source file.
8. Special comments and tool directives#
Although ordinary explanatory comments do not execute as Python statements, certain comment-like forms can be meaningful to the interpreter's source handling, the operating system or development tools.
| Form | Purpose |
|---|---|
| #!/usr/bin/env python3 | A shebang used by compatible operating systems when directly launching an executable script |
| # -*- coding: utf-8 -*- | A source encoding declaration in an allowed first or second line position |
| # type: ignore | An instruction recognised by supporting static type checkers |
| # noqa | A suppression directive recognised by compatible linters |
| # TODO: ... | A human or editor convention for tracking outstanding work |
Python 3 uses UTF-8 as the default source encoding. An encoding declaration is only recognised in its designated location and must comply with the language reference's rules.
The shebang has meaning for direct execution on compatible operating systems; it is not a Python statement. It does not automatically make a file executable.
Tool directives depend on the specific tool and its configuration. Use suppressions narrowly and document the reason rather than disabling useful checks indiscriminately. A TODO comment does not schedule work or implement the missing feature.
9. What makes a good Python comment?#
A good comment explains information that is not obvious from the code. Consider a delivery rule with a specific threshold.
PYTHONdef delivery_fee(order_total): # Orders at or above the free-delivery threshold pay no fee. if order_total >= 500: return 0 return 40 print(delivery_fee(499)) print(delivery_fee(500))
Output:
40
0The comment clarifies the inclusive boundary of the business rule. The two calls illustrate its effect at and below the threshold. This is a simplified example using whole monetary units; production billing code needs explicit currency, precision and rounding rules.
In a real system, an even more valuable comment could identify the approved source of the threshold or explain why a seemingly unusual business condition exists. Do not invent a reason simply to make a comment more elaborate.
Useful comments often explain:
- Why a particular decision or workaround is necessary.
- The meaning and units of a configuration value.
- An external API limitation or compatibility constraint.
- A non-obvious invariant, such as why a lock must be acquired first.
- The conditions under which an operation can safely be retried.
Prefer descriptive names and straightforward logic first. Comments should add context, not compensate for avoidable confusion.
10. Can a comment replace an executable statement?#
No. A comment is not a Python statement and cannot satisfy a grammar requirement for a non-empty suite.
For example, an if block containing only a comment is incomplete and produces an IndentationError when parsed as a complete program.
Use pass when an intentionally empty block is required:
PYTHONif True: # Implementation intentionally deferred. pass print("ready")
Output:
readyThe pass statement is executable syntax that does nothing. The comment merely explains why the block is empty.
Similarly, if you comment out all executable statements inside a function definition, you may need to add pass until the implementation is restored.
11. Common mistakes when writing comments#
Mistaking triple quotes for comment delimiters#
Triple-quoted strings remain string literals. Use consecutive hash-prefixed lines for a genuine multiline comment.
Writing comments that repeat the code#
A comment saying that a counter is incremented directly above an obvious increment rarely helps. Explain why the increment is needed or choose clearer names.
Leaving stale comments after changing the implementation#
A misleading comment can be worse than no comment. Update comments, documentation and tests when changing program behaviour.
Keeping large blocks of obsolete code commented out#
Use version control to preserve earlier implementations. Remove abandoned code unless there is a clear, temporary reason to retain it.
Putting credentials or private information in comments#
Comments may be checked into repositories, copied into packages or included in shared source code. Do not store passwords, API tokens, customer information or other secrets in them.
Ignoring special comment directives during source transformations#
Removing an encoding declaration or a type-checking directive may affect source decoding or tooling. Use language-aware source transformations and preserve meaningful metadata.
12. Python comment best practices#
PEP 8 recommends writing clear, up-to-date comments and using inline comments sparingly. Its default maximum line length for flowing text in comments and docstrings is 72 characters.
Use complete sentences for substantial explanatory comments. Keep comments aligned with the code they describe. Respect your team's conventions where appropriate.
Document important design decisions close to the affected logic. Put detailed architectural context in suitable design documentation rather than forcing it into an oversized code comment.
For code review, ask whether the comment adds information, whether it accurately describes the current behaviour, and whether a clearer name or simpler implementation would remove the need for it.
13. Frequently asked questions#
Do comments slow down Python programs?#
Ordinary comments are processed during source reading and lexical analysis, but do not add ordinary executable operations to compiled code. They do not normally contribute to runtime algorithmic complexity. Special directives and tooling behaviour are separate considerations.
Can Python comments appear inside an expression?#
A comment can appear where a physical line may legally end, including within an implicitly continued expression enclosed in parentheses, brackets or braces. It cannot be inserted in a way that breaks the required grammar or an explicit backslash continuation.
Can I use // for Python comments?#
No. In Python, // is the floor-division operator. Use a hash character for ordinary comments.
Can I comment out multiple lines at once?#
Yes. Most code editors support a toggle-comment command for selected lines. The resulting Python source should use a hash prefix on each commented line.
Are comments visible to the running program?#
Not normally as object metadata. A program that has access to its source file can read or tokenize its comments. Docstrings, by contrast, are normally accessible through __doc__.
14. Interview-ready answer#
Python comments are explanatory source text beginning with a hash character outside a string literal and extending to the end of a physical line. They are not executed as ordinary Python statements. You can write a standalone comment, an inline comment after a statement or a multiline block using a hash on each line. Triple-quoted strings are not comments; in designated positions they can be docstrings. Good comments explain non-obvious decisions, assumptions and constraints, follow relevant style conventions, and remain consistent with the code.
Key takeaways#
- Use # for ordinary comments and consecutive hash-prefixed lines for multiline comments.
- A hash inside a string is not a comment.
- Comments, docstrings and pass have different roles.
- Some special comment forms influence source handling or external tools.
- Write comments to explain intent and maintain them alongside code and tests.
Official references#
- Python Language Reference — Comments
- PEP 8 — Style Guide for Python Code
- PEP 257 — Docstring Conventions
- Python Standard Library — tokenize
- Python Standard Library — ast
- Python Language Reference — The pass statement
Verification note: Nine distinct runnable Python examples were executed locally on Python 3.13.5 and their expected outputs were checked. References are supplied from established knowledge under the authorised offline research exception; live documentation was not checked.
References
- 1.Python Language Reference — Commentsdocs.python.org
- 2.PEP 8 — Style Guide for Python Codepeps.python.org
- 3.PEP 257 — Docstring Conventionspeps.python.org
- 4.Python Standard Library — tokenizedocs.python.org
- 5.Python Standard Library — astdocs.python.org
- 6.Python Language Reference — The pass statementdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design