In Python, comments are used to explain what the code is doing. They are not executed by the computer. Comments are helpful for anyone reading the code later, including your future self!
There are two types of comments in Python:
- Single-line comments: These comments are used for short explanations, and they start with a
#
symbol. - Multi-line comments: These comments are used for longer explanations and are written inside triple quotes (
'''
or"""
).
1. Single-line comments
A single-line comment starts with #
. Everything after the #
on that line is considered a comment and is ignored by Python.
Example of Single-line Comment:
# This is a single-line comment
print("Hello, world!") # This prints a greeting to the screen
In this example:
- The first line is a comment explaining the code.
- The second line has a comment after the code that explains what the
print()
function does.
2. Multi-line comments
Multi-line comments are used when you need to explain something in more detail and require several lines. You can create a multi-line comment using triple quotes ('''
or """
).
Example of Multi-line Comment:
'''
This is a multi-line comment.
It can span multiple lines.
It is useful for explaining complex code.
'''
print("Hello, world!")
Here, the multi-line comment is inside the triple quotes, and it helps explain what the following code might do.
Why Use Comments?
- Clarify your code: Comments make it easier for others (or you) to understand your code later.
- Prevent execution of code: If you don’t want a piece of code to run, you can comment it out temporarily.
- Improve code readability: Comments help explain complex parts of your code.