In Python, comments are used to explain code and make it more readable. Python provides two types of comments: single-line comments and multi-line comments.
1. Single-Line Comment:
A single-line comment starts with a hashtag (#) symbol. Everything following the # on that line is considered a comment and is ignored by the Python interpreter.
Example:
# This is a single-line comment
x = 10 # This is an inline comment
The first line is a full comment.
In the second line, the # symbol is used after the code to explain what the line is doing.
2. Multi-Line Comment:
Python does not have a specific syntax for multi-line comments, but there are two common ways to write multi-line comments:
Option 1: Using Consecutive Single-Line Comments
You can write multiple single-line comments one after another:
# This is a multi-line comment
# using multiple single-line comments.
# Each line starts with a '#'.
Option 2: Using Triple Quotes (String Literals)
You can also use triple quotes (''' or """) to create multi-line comments. This is technically a string literal, but if not assigned to a variable, it is ignored by the Python interpreter and can be used for commenting.
"""
This is a multi-line comment.
It can span multiple lines.
Python will ignore this block of text.
"""
Or using single quotes:
'''
This is also a multi-line comment.
It behaves the same as triple double quotes.
'''
Example:
# This function adds two numbers
def add(a, b):
return a + b
"""
The following line calls the add function
and prints the result of adding 5 and 3.
"""
print(add(5, 3)) # Output: 8
Key Points:
Single-line comments start with #.
Multi-line comments can be done using consecutive # symbols or using triple quotes ''' or """.
Triple quotes are often used for docstrings (documentation) as well.
Let me know if you'd like further examples or have any questions! 😊
0 Comments