Back to articles list Articles
8 minutes read

How to Comment Code in Python

Do you want to learn how to use Python comments properly in your code? We’ve put together a guide to teach beginners how and when to use Python comments to write clean code and increase code readability.

Developers spend much more time reading code than writing code, which makes code readability a very important aspect of creating efficient and maintainable software products. Comments play a key role in enhancing code readability.

As a beginner, you probably haven’t had much experience writing code. Our Learn Programming with Python track consists of 5 fully interactive Python courses that have been carefully designed for beginners. Upon completing this track, you will have tackled a staggering 414 coding challenges – that’s quite a lot of practice!

What Is a Comment?

A comment is a piece of text placed in the code that contains information about what the code does. It could be an explanation to other programmers reading the code or a note for your later use. Comments are ignored by compilers and interpreters, so they have no effect on code execution.

Although Python is a highly intuitive language with a syntax that is easy to understand, programmers still write comments in some parts of their code. In this article, we’ll learn why comments might be necessary as well as how to comment in Python. We’ll also go through some cases where comments are not helpful and you should avoid using them. Before we start our discussion on how and when to write comments, let’s first learn about different comment types in Python.

Python Comment Types

Single-Line Comments: The Basic Syntax of Python Comments

There are different ways of writing Python comments. The way you write a comment depends on the comment length and the choice of the programmer. Let’s first start with a simple example that shows the syntax of comments in Python:

# Initializing first two Fibonacci Numbers 
a, b = 0, 1

Comments begin with a hash mark (#) and a single whitespace character. In the example above, the text after the hash mark is a comment, which gives information about what the code in the next line does. This is an example of a single-line comment.

Inline Comments

We can also write comments on the same line of a statement, following the code. These are called inline comments, which also start with a hash mark and a single whitespace:

learning_rate = 0.02 # Initialize the learning rate

Multi-line Comments

In some cases, a comment does not fit into one line; it extends into multiple lines. These are called multi-line comments. We can write multi-line comments in two different ways.

The first way is by using multi-line strings. The interpreter ignores multi-line strings that are not assigned to a variable, so they can be used as comments. Here is an example:

"""
Regex to check if the input is a valid email address
1. Checks email starts with a set of alphanumeric characters.
2. This is followed by the @ symbol.
3. Another set of alphanumeric characters follow (1 or more)
"""
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,3}\b'

The other way is comments that span out to multiple lines where each line starts with a hash mark. Let’s rewrite the above example in this way:

# Regex to check if the input is a valid email address
# 1. Checks email starts with a set of alphanumeric characters.
# 2. This is followed by the @ symbol.
# 3. Another set of alphanumeric characters follow (1 or more)
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,3}\b'

In this example, writing the entire content of the comment as a single line will result in a very long line, which is difficult to read. Using a multi-line comment makes reading this much faster. Also, we’re able to implement a sequential structure, which makes the comment easier for others to understand.

When to Use Comments

We’ve learned different ways of writing Python comments. Now let’s discuss when it is proper to add comments in our scripts. We’ll go through several cases where a comment serves as a helpful asset in writing clean code.

Informative Comments

Informative comments are used for explaining what a complex piece of code does. Programmers consider writing comments where they think it might be difficult for others to understand the code. A typical use case is writing a comment that explains what a regex (i.e. regular expression) matches, which could be really complex and require others to do some research to understand.

# Regex to match an email address (example: john.doe@example.com)
email_pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"

If you’re not familiar with regular expressions, you’d need to spend a considerable amount of time to understand what the regex pattern in this example matches. Besides, unless the code is written to teach someone regex patterns, what’s the point of making them try so hard to understand it? They can just read the comment and proceed with the rest of the script. This is a great example that demonstrates how useful and functional a comment can be.

Legal Comments

There are cases where comments are necessary for legal reasons (e.g. to provide copyright information). Here is an example where comments are used for specifying copyright information.

# Copyright (c) 2023, Your Name or Company
# All rights reserved.
# Redistribution and use in source and binary forms, with or without   
# modification, are permitted provided that the code retains the 
# above copyright notice.

Explanation of Intent

In some cases, it’s very helpful to explain the intent so that other developers have some understanding as to why you chose to write a piece of code in the way you did. Here is a simple example with a comment to indicate the usage of list comprehension instead of a for loop:

# Using list comprehension instead of a for-loop for performance reasons
squared_values = [x**2 for x in range(1000)]

Commenting Out Code for Debugging

We mentioned that comments are ignored by the interpreter and compiler. So when we’re debugging a script or searching for a bottleneck that’s causing performance problems, we can comment out a piece of code and run the rest of it. If the error or performance issue is fixed after commenting out a specific part of the script, we can assume the commented-out part is problematic – or at least investigate further into the commented-out part to find the exact issue.

In the following example, the execution of the generate_tax function is commented out. If a problem is solved after commenting out this line, we can investigate this function’s code to solve the issue:

# calculated_tax = generate_tax(income, tax_rate)

Bad Comments

We should not use comments to explain poorly written code. It’s best not to use comments unless necessary. If you feel like your code needs comments, try to rewrite it so that it’s clear and using comments becomes unnecessary.

In the following example, the function name is self-explanatory and it’s quite clear what it does. Hence, the comment above the function name is redundant.

import math
# Calculates the area of a circle
def calculate_circle_area(radius):
    return math.pi * radius * radius

We mentioned earlier that we sometimes comment out a piece of code for debugging. After this process is completed, we might end up having code that is no longer needed. In such cases, we should not leave it as commented-out code. Instead, we should delete that piece of code and keep the script clean and more readable. Since almost all codebases are managed with a version control system (e.g. Git), we can always revert to another version if a commented-out piece of code is ever needed again.

It’s very important to keep comments up to date as the code evolves. Otherwise, they would do more harm than good and be misleading.

In the following example, a comment is used to indicate the tax rate. However, the commented tax rate is different from the one used in the actual code. Thus, someone reading this code might think the code is wrong and attempt to update it:

def calculate_tax(income):
    # tax rate is 20%
    tax_rate = 0.25
    return income * tax_rate

We should avoid using comments when they’re not necessary. Comments don’t impact the execution of code since they’re ignored by the compiler and interpreter. However, they are a fundamental part of code readability. We need to use them carefully as a tool to add informative power.

Now You Can Use Comments in Your Python Journey

And that’s what you need to know about commenting in Python!

Python is one of the most popular programming languages. It’s easy to learn, but you can’t learn it in a day. You need a well-designed learning process with a lot of practice.

The starting point is to find a good resource, which is an essential ingredient for an efficient learning journey. Read this article if you’d like to learn about the 5 best resources to learn Python. After you make your choice, try to code everyday. Consistency is the key to a successful learning path. Here are some additional tips that’ll help you speed up your learning process.

Happy learning!