Python Comments
Python · Getting Started
Theory
A comment is text in your code meant for humans. In Python a comment starts with # and runs to the end of that line; the tokenizer throws it away before the code is compiled, so it has zero effect on how the program runs. You can put a comment on its own line or after code on the same line, like total = sum(sales) # add up all sales.
Python has no true multi-line comment syntax. A triple-quoted string such as """some text""" is actually a string value; if it is not assigned to anything it is simply evaluated and discarded. When it is the very first statement inside a module, function or class it becomes that object's docstring, which help() and tools can read through the __doc__ attribute. So use # for comments and triple quotes for documentation.
Why we use it
Comments explain why the code does something, which the code alone cannot say. They help teammates, and your future self, understand a tricky formula or a business rule, and # is the quickest way to temporarily disable a line while debugging.
When to use it
Comment the reason behind non-obvious logic, assumptions and TODOs. Do not comment what is already obvious (x = x + 1 # add one). For describing what a function does, write a docstring instead of a # block.
How it works
- Python reads a line of source code
- Is there a # outside a string? Yes: Drop everything from # to line end. No: Keep the whole line as code.
- Lone triple-quoted string first in a def/class? Yes: Store it as the docstring. No: Evaluate and discard it.
- Compile the remaining code to bytecode
- Run the code; comments never execute
Syntax
# single line
""" multi-line comment """Example
# Calculate total sales
total = sum(sales)Key points
- Start single-line comments with #
- A # inside quotes is just a character, not a comment: '#1 seller'
- Triple quotes are often used for multi-line docstrings
- Docstrings are stored on the object; # comments are discarded
- Good comments explain why, not what