How to write multiline comments in Python
December 01, 2021
How to write a multiline comment in Python:
It is a good practice to comment code. It helps other developers to read and understand a new project. Comments are ignored by the compilers and they don’t make the code slow. In this post, I will show you how to write a multiline comment in Python and how to comment a line quickly in VSCode and PyCharm.
Single line comment:
You need to add a # before a line to mark it as a comment line.
# printing hello world
print('Hello World')
# printing hello world again
print('hello world....')
I added two comment lines in this code snippet. It will not throw any IndentationError error.
But, it will be an error:
# printing hello world
print('Hello World')
# printing hello world again
print('hello world....')
print('hello world....')
IndentationError: unexpected indent
Multiline comments:
For a multiline comment, you need to start and end it with """.
For example,
"""
This is a
multiline string
"""
def print_msg(msg):
"""
:param msg: message to print
:return: none
"""
print(msg)
print_msg('Hello World')
Another way:
You can also use # before each line to comment out multiple lines:
# This is a
# multiline string
def print_msg(msg):
# :param msg: message to print
# :return: none
print(msg)
print_msg('Hello World')
Comment out multiple lines in PyCharm or VSCode:
If you want to comment out multiple lines in IDE like PyCharm or VSCode, just select the lines and press Cmd + / on Mac or Cntrl + / on Windows or linux. It will comment out the lines.
By default, it will add a # before each of these lines, i.e. it will not use """.
Comments or docstring:
Make sure to do proper identation if you are using triple quotes. For example:
def print_msg(msg):
"""
:param msg: message to print
:return: none
"""
print(msg)
print_msg('Hello World')
This will throw an IndentationError.
But if you use #, it will work:
def print_msg(msg):
# :param msg: message to print
# :return: none
print(msg)
print_msg('Hello World')
It will work.
Because, if you use triple quotes, python interpreter doesn’t ignore those lines. If you use #, these lines are ignored.
Triple quotes are called docstrings and these are used to document a python module. So, if you want to comment multiple lines, not documentation, # is preferred.