How to Add Multiline Comments in Python?

Python does not have a specific syntax for multiline comments like most other programming languages do. However, there is a common workaround to achieve a similar effect, which is to use triple quotes (''' or """), for example, like so:

"""
This is a multiline comment.
You can write as many lines as you want here.
This will not be executed or cause any syntax errors.
"""

print('foo')

A multiline string enclosed in triple quotes is ignored by Python (unless it's assigned to a variable or used in a specific way). Therefore, you can use it to add multiline comments, even though its typically used for creating docstrings.

It's important to note that using single-line comments (starting with #) is generally recommended for adding comments to your code because docstrings are specifically intended for documenting functions, classes, and modules.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.