Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. Comments enhance the readability of the code and help the programmers to understand the code very carefully.
There are three types of comments in Python:
- Single line Comments
- Multiline Comments
- Docstring Comments
Comments in Python
In the example, it can be seen that Python Comments are ignored by the interpreter during the execution of the program.
Python3
# sample comment name = "neveropen" print (name) |
Output:
neveropen
Types of Comments in Python
Single-Line Comments in Python
Python single-line comment starts with the hashtag symbol (#) with no white spaces and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the Python Comments. Python’s single-line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment:
Example:
Python3
# Print “Lazyroar !” to console print ( "Lazyroar" ) |
Lazyroar
Multi-Line Comments in Python
Python does not provide the option for multiline comments. However, there are different ways through which we can write multiline comments.
Multiline comments using multiple hashtags (#)
We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be considered as a single-line comment.
Python3
# Python program to demonstrate # multiline comments print ( "Multiline comments" ) |
Multiline comments
String Literals In Python
Python ignores the string literals that are not assigned to a variable so we can use these string literals as Python Comments.
Single-line comments using string literals
On executing the above code we can see that there will not be any output so we use the strings with triple quotes(“””) as multiline comments.
Python3
'This will be ignored by Python' |
Multiline comments using string literals
Python3
""" Python program to demonstrate multiline comments""" print ( "Multiline comments" ) |
Multiline comments
Docstring in Python
Python docstring is the string literals with triple quotes that are appeared right after the function. It is used to associate documentation that has been written with Python modules, functions, classes, and methods. It is added right below the functions, modules, or classes to describe what they do. In Python, the docstring is then made available via the __doc__ attribute.
Example:
Python3
def multiply(a, b): """Multiplies the value of a and b""" return a * b # Print the docstring of multiply function print (multiply.__doc__) |
Output:
Multiplies the value of a and b
Advantages of comments in Python
Comments are generally used for the following purposes:
- Code Readability
- Explanation of the code or Metadata of the project
- Prevent execution of code
- To include resources