Comments in Python are the lines that are ignored by the interpreter during the execution of the program. It can enhance the readability of your python code and help other programmers to understand the code easily.
Types of Comments in Python
Here are three types of comments in python. They are:
- Single-Line Comments
- Multi-Line Comments
- Docstring
Single-Line Comments
Python single-line comment starts with the hashtag symbol (#
) with no white spaces and lasts till the end of the line.
Example:
# This is the first single-line comment in Python print("Hello, World!") # This is the second comment
This example contains tow single-line comments.
Multi-Line Comments
In Python, multi-line comments can be created using triple quotes ("""
or '''
) or by using consecutive single-line comments with the hash symbol(#
).
Using Triple Quotes
Triple quotes are often used for multiline comments. The text enclosed within triple quotes is ignored by the interpreter if not assigned to a variable.
Example:
""" This is a multiline comment using triple quotes It spans multiple lines """ print("Hello, World!")
Consecutive Single-Line Comments
Another way to create multiline comments is by using consecutive single-line comments with the hash symbol (#
).
Example:
# This is a comment # written in multiple lines # using consecutive single-line comments print("Hello, World!")`
Docstring
Python docstring is the string literals with triple quotes that appears right after the definition of a function, method, class, or module. It is used to describe what they do. In Python, the docstring is then made available via the __doc__
attribute.
Example:
def multiply(a, b): """Multiplies the value of a and b""" return a*b # Print the docstring of multiply function print(multiply.__doc__)