Adventures in Machine Learning

Python Comments: Best Practices for Readable and Maintainable Code

Python Comments

If you’re new to Python programming, it’s essential to know that comments are an essential part of creating a reliable, maintainable and readable program. A comment is a string of text that is ignored by the Python interpreter.

Comments help you, the programmer, to communicate ideas, assumptions, details, or defects about your code effectively. Comments act as guidance for other programmers or future versions of yourself who must work with the code.

They explain what the code does, why it does it, and how it does it. This article will examine how to write comments in Python, including best practices.

How to Write Comments in Python

Python uses a hash character ‘#’ to indicate that the proceeding text is a comment. Comments start with the hash character, followed by the whole comment text.

You can use comments before a single line of code or next to a code statement. Python ignores everything after the hash character, so the text is ignored when the interpreter reads your program.

For example, if you have written a function to calculate the area of a circle, you can add some comments to explain what the function does:

# Defining a function to calculate the area of a circle

def calculate_circle_area(radius):


Calculate the area of a circle using the radius parameter. Parameters


radius: int or float

The radius of the circle.




The area of the circle. “””

pi = 3.14

area = pi * (radius ** 2)

return area

This comment clearly explains the purpose of the function, what parameters it expects, and its output.

With such information, you or any other programmer can understand what the function does and how to use it.

Python Comments Examples

Let’s look at a few more examples and how they can be useful. 1.


# The following code declares a variable named x and sets its value to 5. x = 5

This comment explains the purpose of the code statement and makes it clear to anyone reading the code what the variable x represents.

2. Functions

# A function to calculate the sum of two numbers.

def add(x, y):


This function calculates the sum of two numbers. It accepts two parameters and returns their sum.



x : int or float

The first number

y : int or float

The second number



int or float

The sum of the two numbers. “””

return x + y

This comment explains the meaning of the function and its parameters.

It also shows what is expected to be returned and what types of values are returned. 3.


# Defining a customer class

class Customer:


A customer class contains information about the customer, including their name,

contact information, and order history. Attributes


name : str

The name of the customer

email : str

The customer’s email address.

order_history : list

A list containing all the orders made by the customer. “””

def __init__(self, name, email): = name = email

self.order_history = []

This comment explains what the customer class does and what attributes it has.

Using Python Docstring as Multiline Comment

Python has a specific type of comment called a docstring. A docstring is a string literal that is an attribute of an object, and its primary purpose is to document the object’s purpose, behavior, and interface.

Docstrings are usually used to document modules, functions, classes, and methods.

For example, consider a function that converts a temperature from Celsius to Fahrenheit, which also allows the user to specify whether they want to display the result using the Kelvin temperature scale.

def convert_temperature(celsius, display_k=False):


Convert a given temperature from Celsius to Fahrenheit. Parameters


celsius : float

The temperature in Celsius to be converted.

Keyword Arguments


display_k : bool, default=False

If True, the function displays the temperature in Kelvin. Returns



The converted temperature in Fahrenheit or Kelvin if requested.


fahrenheit = (celsius * 1.8) + 32

if display_k:

return (fahrenheit + 459.67) * 5/9

return fahrenheit

The docstring in this function provides useful information about what the function does, what parameters and arguments it uses, and what it returns. It also explains the default value of the keyword argument ‘display_k.’

Is it a good idea to use Docstring to specify long multiline comments?

A docstring can span multiple lines, and it is tempting to use docstrings as multiline comments, but this is not a good idea. Docstrings are intended explicitly to be used for documentation, and they can cause problems if misused.

First, using docstrings as comments can make code harder to read and maintain. Code blocks with long multiline comments can become cluttered and difficult to navigate.

Second, it can lead to problems with software documentation. Documentation tools like Sphinx expect to find docstrings that contain documentation of a Python module, function, or class.

Python Multiline String as Multiline Comments

If, for whatever reason, you need to use multiline comments in your Python code, you can use Python multiline strings. In Python, you can identify a multiline string by enclosing the text within triple quotes.

With multiline strings, you can include any text you want, including comments.

For example, consider the following code:


This program demonstrates how to print the Fibonacci sequence.


def fibonacci(n):


Returns the nth Fibonacci number using recursion. Parameters


n : int

The nth number in the Fibonacci sequence.




The nth Fibonacci number. “””

if n <= 1:

return n


return fibonacci(n-1) + fibonacci(n-2)

# Print the first ten numbers in the Fibonacci sequence.

for i in range(10):


In this example, we use a multiline string to provide a description of the program’s purpose. The string is not assigned to any variable, so Python interprets it as documentation that gets ignored.

Python Commenting Best Practices

To making commenting effective, here are some best practices:

1. Use a commenting system: Using a commenting system helps you organize your comments and make them easier to read and understand.

You should have a standard system for documenting your code, such as using docstrings, inline comments, or multiline comments.


Write meaningful comments: Write comments that help readers understand what the code does, how it works, or why it exists. Avoid writing comments that repeat what the code does.

3. Useless comments: Avoid comments that add no value, such as comments that state the obvious or comments that don’t provide any additional insights.

4. Stick to commenting policy: Your comment should follow a commenting policy that ensures that the comments remain consistent, clear, and useful across the entire project.

5. Use commenting shortcuts: Use commenting shortcuts such as CTRL+/, which automatically adds the comment character and can speed up the commenting process.


Comments play a crucial role in documenting and communicating ideas about Python code. An excellent comment is essential to working in a team and can be a critical tool in making your code understandable, maintainable, and offloading some of the cognitive workload of understanding code.

Proper commenting helps you write code faster, and it makes it possible to write code that lives long enough to outlast the current project and team. By using the best practices discussed in this article, you’ll be able to improve the quality of your Python code and communicate more clearly with other developers.

Python comments are vital in creating a readable, maintainable, and reliable program. This article outlines how to write comments in Python, including best practices.

Some of the key points include using docstrings as multiline comments, employing meaningful comments, adhering to commenting policies, and using commenting shortcuts. Effective commenting enhances teamwork, increases code quality, and ensures that the code can outlive the current project and team.

The takeaway for developers is to develop a commenting system, write useful comments, stick to commenting policies, and use commenting shortcuts to improve code quality communication with peers.

Popular Posts