Comments are used for documentation purposes, but they are overlooked by the compiler during the execution of code. Adding comments is like writing notes in your code. It helps you understand your code better, makes it easier for others to read, and lets your team members know how your code functions. 

This blog post will demonstrate various comment-creation methods in Python.

What are Comments in Python?

In Programming languages like Python, developers use comments to gain a better understanding of code. Well-structured comments can make code easier to read and maintain. Single-line comments and multi-line comments fall under the category of comments.

Method 1: Single-Line Comments in Python Using # Sign

In Python, to use single-line comments, simply place a hash symbol/character (#) at the beginning of a line. Here’s an example:

# print("2+3")#print a message
print("My name is Peter")

The first line of code is not compiled because of #. Hence the 2nd line is displayed.

Method 2: Multi-Line Comments in Python Using # Symbol

In Python, to implement multi-line comments, specify a hash symbol/character (#) at the beginning of each line. Let’s implement multi-line comments with the help of an example:

# print("Hello there")
# print("How are you doing")
# print("Welcome to Python Programming")

It can be seen that all the 3 lines are commented so no output is displayed.

Note: This approach is not recommended by developers, as it is time-consuming.

Method 3: Multi-Line Comments Using Docstrings 

The most efficient method to make multi-line comments in Python is with the help of Docstrings. In Python, you can use docstrings with the help of triple-quoted punctuation marks “”” “””. Let’s demonstrate docstrings using an example:

def multiply_numbers(x, y, z):
    """
    A function that returns the multiplication of
    3 numbers
    """
    return x*y*z
print(multiply_numbers(3, 4, 5))

It can be seen that the program compiled successfully and returned the addition of 2,3 and 4 whereas the docstring is not compiled.

Note: While using docstrings for commenting, remember the indentation and spaces. If the indentation of a program is disturbed, it will throw an error named “IdentationError”.

Conclusion

Developers frequently use a technique called “commenting” to help them better understand the code. Place a hash sign(#) at the start of every line to use a single-line comment. To comment on multiple lines in Python you can use docstring (“”” “””) which is the most convenient and efficient method. This article has illustrated different methods of creating multi-line comments in Python.