89DEVs

Python: How to comment multiple lines?

Use multiple single line comments (#) to comment multiple lines in Python.

Unfortunately Python doesn't have a multiline comment syntax like other programming languages. For example in PHP it is possible to comment multiple lines with the following multi-line comment syntax.


/* 
This is a multi-line comment in PHP, 
it doesn't work in Python.
*/


Use multiple single line comments (#)

In Python the best option is to use multiple single line comments (#) to imitate the behaviour of a multiline comment. According to the Python PEP8 Style guide "each line of block comment starts with a # and a single space". It is easier to read the comment if it's separated from the # by a single space. # This is a Python comment # over multiple lines # using single line comments print('comments work') Like expected only the print statement is returned and not the comment. comments work

The problem with docstrings

It is not recommended to use triple-quoted strings (''') so called docstrings to comment multiple lines. Docstrings are generally used to describe the functionality of public modules, functions, classes and methods. They are a way to insert text, but are not real comments. Docstrings should only be used as intended inside a function, class or method to describe what it does. While comments can be inserted anywhere to explain how the code works. When used as multi-line comments they can have unexpected behaviour. ''' This is a Python comment over multiple lines using triple-quoted strings ''' For example the Python terminal returns a string. It is not the result you would expect from a real comment. '\nThis is a Python comment\nover multiple lines\nusing triple-quoted strings\n'

How to write good comments

Comments are considered good practice in programming to describe and explain the code. So use them as often as necessary and describe in a concise and easy to understand way the functionality of the code. It is easy to understand code after you wrote it, but after a few years this has changed. That's why code should contain clear comments to make it maintainably over time. It is also important to understand that comments can help other people reading your code. Good commenting can help them save time to understand your code by explaining the logic behind it. Like your code a good comment shouldn't repeat itself, save your and others time by being concise and still explanatory. Use multiple single line comments (#) to extend your comments over multiple lines. The more information the comment contains the better it is usually. Some IDEs provide shortcuts to insert single line comments over multiple lines more effectively.

                
        

Summary


Click to jump to section