PY_CHAPTER_2_TOPIC_2
PY_CHAPTER_2_TOPIC_2
Comments are non-executable lines in code that are used to describe the
functionality, clarify logic, or add notes for developers. They are ignored by the
Python interpreter when the program is run.
1. Single-line comments
2. Multi-line comments
1. Single-Line Comments
In Python, single-line comments start with a hash symbol #. Everything after the #
on that line is considered a comment and is ignored by the Python interpreter.
Syntax:
Example:
In this example, only the print() statement will be executed, and everything
after the # is ignored.
2. Multi-Line Comments
While Python does not have a specific syntax for multi-line comments like other
languages (such as /* ... */ in C or Java), you can achieve multi-line
comments in two main ways:
You can write multiple single-line comments by placing # at the beginning of each
line.
# This is a comment
# that spans
# multiple lines
print("This is a valid multi-line comment")
Option 2: Using Triple Quotation Marks (''' or """)
'''
This is a multi-line comment.
It can span multiple lines
and is useful for large blocks of comments.
'''
print("Triple quotes can be used as multi-line
comments")
or
"""
This is another way to create
a multi-line comment in Python
using triple double quotes.
"""
print("Using triple double quotes")
Note: While this method is widely used for comments, technically it is a string that
isn't assigned or used in the code. Python ignores such unassigned strings, which
makes them act like comments.
In this example, the comments are unnecessary because the code is simple and
self-explanatory.
4. Inline Comments
An inline comment is a comment that is written on the same line as the code. These
should be used sparingly and only when necessary to clarify specific code.
Syntax:
x = 10 # Assign 10 to variable x
Best Practice: Leave at least two spaces before the # symbol in inline comments
for better readability.
5. Using Docstrings for Documentation
Though not exactly comments, Python supports docstrings, which are multi-line
strings used to document modules, classes, functions, and methods. Docstrings are
written inside triple quotes """ or '''.
Example:
def greet():
"""
This function prints a greeting message.
It doesn't take any arguments or return any value.
"""
print("Hello, World!")
Conclusion