In Python, comments are lines of text that are ignored by the interpreter and not executed as part of the program. They are used to add notes and explanations to the code, making it easier to understand and maintain.
There are two types of comments in Python:
Single-line comments start with the hash symbol (#
) and continue to the end of the line. They are used to add a brief explanation or a note about the code on the same line.
For example:
# This is a single line comment
x = 5 # This is also a single line comment
Inline comments are used to add notes or explanations about a specific part of a line of code. For example:
x = 5 # This variable is used to store the value 5
Multi-line comments, also called block comments, start with three quotes ("""
or '''
) and continue until the next set of three quotes. These can span multiple lines and are used to add detailed explanations or notes about the code or to temporarily disable a section of code.
For example:
"""
This is a multi-line
comment that spans
multiple lines
"""
print("Hello")
'''
This is also a multi-line
comment that spans
multiple lines
'''
Python also supports a special type of comment called documentation strings (or docstrings for short). These are enclosed in triple quotes ("""
) and are used to provide documentation for a module, function, class, or method. Docstrings can be accessed using the built-in help()
function or the __doc__
attribute. For example:
def add(a, b):
"""
This function takes in two parameters and returns their sum
"""
return a + b
print(add.__doc__)
This function takes in two parameters and returns their sum
It is a best practice to use comments in your code to explain what the code is doing, especially for complex or non-obvious code. This makes it easier for others (or yourself) to understand and maintain the code.
Note: Comments are not executed by the interpreter and are ignored by the interpreter, they are used to make the code readable and understandable to human readers.