Comment
What are comments?
Comments in Python are annotations in the source code of a Python program. They are added with the purpose of making the code easier to understand and use. Comments are intended for human understanding and do not have any impact on the execution of the program.
There are two types of comments in Python:
- Single-line comments
- Multi-line comments
Single-Line Comments
Single-line comments in Python start with the hash character (#
). Everything to the right of the #
on the same line is considered a comment.
Here’s an example:
In the above code snippet, # This is a single-line comment
is a comment that the Python interpreter ignores. The second line includes an inline comment, # This is an inline comment
, which follows a statement.
Multi-Line Comments
Python does not have a built-in syntax specifically for multi-line comments. However, programmers often use multi-line strings as multi-line comments.
Python’s multi-line strings are enclosed within triple quotes ("""
or '''
). They start and end with three quote marks.
It is important to note that multi-line strings aren’t ignored by Python interpreter as actual comments, hence they have to be used very judiciously. They can be used as multi-line comments when they are not a part of a function or class etc., and otherwise they are treated as docstrings.
PEP 8 and Comments
According to Python Enhancement Proposal (PEP) 8, a style guide for Python code, you should include comments that contradict the code, as assumptions aren’t always correct. Also, it suggests to keep comments up-to-date with code changes as outdated comments can mislead others.
Comments and Code Readability
Apart from explaining non-obvious parts of your code, comments can serve as a way to structure your programs, like when using comments to mark different sections of your code.
Moreover, comments are used for “commenting out” code, i.e. prevent lines of code from being executed while debugging.
In the above Python code, the first print statement will not be executed because it’s commented out. It can be useful technique while testing and debugging code.
Understanding how to properly use comments can make your code much more readable and easier to maintain, not only for yourself but for others who may work with your code as well.