Comments in Python
Learn how to write clean, readable, and professional Python code using single-line comments, multi-line comments, and documentation comments (Docstrings).
Single-line Comments
In Python, single-line comments start with `#`. Everything after `#` on that line is ignored by the Python interpreter.
1. Basic Single-line Comment
Everything after `#` on that line is ignored by Python.
2. Inline Comment (End of Line)
Inline comments are placed at the end of a line to explain it quickly.
3. Debug Notes / TODOs
Common practice: using keywords like TODO, FIXME, NOTE so they can be searched easily in editors like VS Code.
Multi-line Comments
Python does not have a special multi-line comment symbol like some languages. Instead, developers either use multiple `#` lines or triple-quoted strings (`""" ... """`) for longer explanations.
1. Multiple # Lines
The most common and recommended way to write multi-line comments in Python is using multiple `#` symbols.
2. Temporarily Disable a Code Block
You can comment out multiple lines to prevent them from executing.
3. Triple-Quoted String as Big Note
Triple-quoted strings can be used as large notes, but they are technically strings, not true comments.
Documentation Comments (Docstrings)
In Python, documentation comments are called Docstrings. They use triple quotes (`""" ... """`) and are placed inside functions, classes, or modules. Tools and IDEs can read docstrings to generate documentation.
1. Documenting a Function
A docstring is written immediately below the function definition.
2. Accessing a Docstring
You can access a function’s docstring using the `__doc__` attribute.
3. Documenting an Async Function
Async functions can also have docstrings just like normal functions.