In Python, comments are used to add explanatory notes to your code. They are ignored by the Python interpreter and do not affect the execution of the code. Here are some examples of comments in Python:
Types of Comments in Python
- Single Line Comments
- Multi Line Comments
Single Line Comments
Single line comment is start with a hash(#) symbol. The statement start with hash(#) symbol till the end of the line treated as comment.
# This is a single-line comment x = 5 # Assign the value 5 to variable x
Here, the first line with hash(#) symbol is comment line. and the second line, print(“Hello, World!”) is a statement.
Multi Line Comments
When we want to have more than one line comment, it becomes tedious job to mark every line with single line comment with hash(#) symbol.
In order to use multi line comments, we can use comment line inside triple double quotes (“””) or triple single quotes(”’) in the beginning and ending of the comment statement block.
""" This is a multi line comment which make non-executable to more than one line. """ OR ''' This is a multi line comment which make non-executable to more than one line. '''
Although, in python there is only single line comment supported. Multi line comments are not available in python.
Comments inside the triple quotes are regular strings with the exception that they can span multiple lines. That means memory allocated to these strings internally. If these strings are not assigned to any variable, then these are removed from memory by the garbage collector and hence can be used as comments.
Comments can also be used to provide documentation for functions, classes, and modules using docstrings:
def square(x): """ Returns the square of a number. :param x: The number to be squared. :return: The square of x. """ return x ** 2
In this example, the docstring provides information about the function’s purpose, parameters, and return value.