Textlogo_codingem_white

Programming tips for everyone

Block 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 a multi-line comment:

'''
This here
is a longer
multi-line comment
also known as docstring.
'''
print("Yay")


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:

savings = savings * 1.02 # Multiply savings by interest rate


Docstrings in Python

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.


Multiline Comments in Python

To your surprize, Python does not support multiline comments. You can use multiline docstrings as multiline comments instead.


Conclusion

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

Share on facebook
Share on twitter
Share on linkedin

Related Articles

Artturi Jalli

Technical Writer

Entrepreneur, Software Engineer, Mobile App Dev, MSc Physics Student, And Tech Enthusiast from Finland

artturi@codingem.com

My Personal Favorites
Sponsor

Buy an Online Course

Lorem ipsum dolor sit amet consectetur adipiscing elit dolor
Explore Categories

Favorites