Python Programming : A Classroom Approach.
2.4
Python Comments
In Python, comments are explanatory notes that you can
add to your code to make it more readable and understandable. The Python
interpreter ignores these comments when executing the code. Comments are
crucial for documenting your code and helping others (and yourself!) understand what your code does.
There are two main types of comments in Python:
i.
Single-line comments: These
start with a hash symbol (#
) and
continue until the end of the line.
Example :
#
This is a single-line comment
print("Hello,
world!") # Prints Hello, world!
ii.
Multi-line comments: Python
doesn’t have a specific syntax for multi-line comments, so we use triple quotes
('''
or """
) to create multi-line strings that
the interpreter ignores.
Example :
”’
This
is a multi-line comment.
It
can span multiple lines and is useful for longer explanations.
”’
"""
This
is another way to write a multi-line comment.
It’s
also a string literal, but it’s not assigned to a variable, so it’s ignored.
"""
iii.
Documenting code with comments: Use
comments to explain the purpose of your code, the logic behind it, and any
assumptions you’ve mad. This makes your code easier to understand and maintain .
Example :
"""
This prints
a simple greeting message to the console.
It
demonstrates how to document code using a docstring.
"""
print("Hello, world!")
Comments are your friends! Use them liberally to make
your code clear and understandable for everyone.