Comments in Python

Python Code

Leaving code comments sometimes helps to clarify your intent. In this guide, you learn different types of code comments in Python: Inline comments, documentation strings (multi-line comments), and block comments.

If you need a quick answer, here is a one-line comment in Python:

# Multiply savings by the annual interest rate
savings = savings * 1.02

And here is a multi-line comment:

This here
is a longer
multi-line comment
also known as docstring.

Different Comment Types in Python

In Python, comments begin with #. There are no multi-line comments in Python. However, you can create a documentation string that behaves like a multiline comment.

Let’s take a closer look at each comment type:

Block Comments in Python

The block comment explains the code that follows it. This type of comment is typically indented to the same level as the code that follows.

For instance:

# Multiply savings by the annual interest rate
savings = savings * 1.02

Inline Comments in Python

An inline comment is a comment on the same line as the piece of code it is commenting on. For example:

# Multiply savings by the annual interest rate
savings = savings * 1.02

Docstrings in Python—Python Comments on Multiple Lines

A documentation string or a docstring is a string created with triple quotes """. It is used to document the code by placing the documentation string before the code block. This can be a one-line comment or a multi-liner.

For instance:

This function accumulates
the savings taking into
account the annual interest
rates in addition to deposits
 def analyze_savings():

Under the hood, a docstring is a string literal that is not ignored by the Python interpreter (unlike ordinary comments). Thus a docstring cannot be classified as a code comment, but it can be used to comment code.


Make your code readable enough that it can express itself without comments. However, if you need to comment on the code:

  • Start a comment block or an inline comment with # sign.
  • For multiline comments use docstrings

You May Find Insightful

For Loop Examples in Python

10 Useful Python Snippets to Code Like a Pro

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *