How to Comment Code in Python

Leaving code comments might sometimes help clarify your code.

There are 3 unofficial comment types in Python.

A “block comment”:

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

An “inline comment”:

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

A “multi-line” comment that misuses a docstring:

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

Commenting Code in Python

To add a comment in Python, use the hashtag operator # before starting to type the comment.

Before digging into the details, remember that commenting code is usually bad. You should always try to write code that expresses itself clearly enough so that no comments are needed.

Let’s take a look at an example of this piece of code. It implements the 1D random walk. As you can see, the code is littered with comments explaining the lines below.

import numpy as np
import random

def randwlk1d(n):
    x, y = 0, 0
    # Generate the time points (tps) [1, 2, 3, ... , n]
    tps = np.arange(n + 1)
    
    # Initialize positions array ps to the starting point y
    ps = [y]
    
    # Specify directions up and down (U and D)
    ds = ["U", "D"]
    for i in range(1, n + 1):
        # Randomly select either U or D (up or down)
        s = random.choice(ds)
        
        # Move the object up (U) or down (D)
        if s == "U":
            y += 1
        elif s == "D":
            y -= 1
        # Add each position to the ps list to track the positions
        ps.append(y)
        
    # Return timepoints and positions as (tps, ps)
    return tps, ps

But what if instead of commenting on the code, we just used easier-to-understand variable names?

import numpy as np
import random

def randomwalk1D(n):
    x, y = 0, 0
    timepoints = np.arange(n + 1)
    positions = [y]
    directions = ["UP", "DOWN"]
    
    for i in range(1, n + 1):
        step = random.choice(directions)
        
        if step == "UP":
            y += 1
        elif step == "DOWN":
            y -= 1
            
        positions.append(y)
        
    return timepoints, positions

As you can see, this improves the code quality by a ton. There is no need to use comments anymore as the code speaks about itself.

However, it can sometimes be useful to be able to comment code. So let’s see what kinds of comments there are in Python.

Different Comment Types in Python

In Python, comments begin with #. Officially, there are no multi-line comments nor inline comments in Python.

But there are three commonly used ways to add comments in Python:

  1. One line before the code.
  2. At the end of the code line on the same line.
  3. On multiple lines using triple-quotation marks.

    Here are the unofficial names of these three comment types:
  1. Block Comments
  2. Inline Comments
  3. Multiline Comments or Docstrings.

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

1. Block Comments in Python

The block comment explains the code that follows. This type of comment is usually placed one line before the piece of code it expresses. A block comment is typically indented to the same level as the code in the next line.

For instance:

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

2. Inline Comments in Python

An inline comment is a comment on the same line as the code. Although this officially classifies as a comment like any other, sometimes you may hear developers calling it an inline comment.

For example:

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

3. Multiline Comments 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.

But this is actually not meant to be used as a comment. Instead, it is used as a documentation string. In Python, there is a built-in function help() you can call on any Python object. If that object specifies a docstring, the help() function shows that in the console. This can save you time from diving into the docs.

For instance:

def greet(name):
    """ Greets a person with their name. """
    print(f"Hello, {name}")

Now you can call help() on the greet() method anywhere where it is accessible:

help(greet)

Output:

Help on function greet in module __main__:

greet(name)
    Greets a person with their name.

Under the hood, a docstring is a string literal that is not ignored by the Python interpreter because of the help() function. Thus a docstring cannot be classified as a code comment. However, you could use it to comment code without problems. But this is against best practices. Read more about docstrings and their purpose in Python.

Conclusion

Try to write code that is readable enough to express itself without comments. Ideally, your code should be clear enough that no comments are needed.

However, if you need to write comments, you can do so with Python’s hashtag # operator.

If you need to add multiline comments, you should use consecutive # operators. This is because Python has no multiline comments. A hacky way to add multiline comments is using the docstring (triple quote string """) which is intended to document code.

Scroll to Top