Including comments in the program is very much required from a code readability perspective and including comments in the program is mandatory and it depends on the organization/project coding practice. In Python, there are two types of comments i.e. single-line comments and multi-line comments.
Single Line Comments: These comments are generally used to write comment in single line and it its start with hash symbol (#) . The complete line is treated a comment.
# Description: Python tutorial on datatypes.
Multi line comments: In case you want use multiple line to include comment then one option is to include # in the beginning of each line. Python has provided to solution to this problem as well, you can use multi line comments. They start with triple double quotes (“””) and should be end with triple double quotes (“””). You can also use triple single quotes (”’) despite of double quotes.
''' Description: Python tutorial on Python Data Types will present a brief overview of the various built-in data type or user define data types. '''
""" Description: This program demonstrates the use of the function to calculate the sum of two numbers. """
Docstring in Python.
Now, its time to disclose some interesting facts around multi-line comments. In reality, Python only supports single-line comments. Multi-line comments are regular strings with an exception that they can extend to multiple lines.
The memory will be allocated to these string normally and if these strings are not assigned to any variable then they would be removed from the memory by the garbage collector. Thus, these multi-line strings can be used as comments.
If you use these strings as the first statement in class or function or method, then these strings would be treated as documentation strings or docstrings. It’s always recommended to avoid using multi-line comments because they occupy internal memory and it also requires interpreters processing. Following is an example of docstring in python function.
# Example of Docstings in Python.
# Function to calculate the total.
''' Function to calculate total of two numbers '''
print("Total is :", (a+b))
# Call the function.
Total is : 3