How to Write Comments in Python 3

Learn how to write comments in Python to make your code easily readably for easy collaborations with other developers.

Writing Comments in Python 3
Writing Comments in Python 3

Comments in programming have proven to be very useful. They can describe what a specific code does so that other developers can understand it, they make the code more readable and can act as notes for reminders. They can also be used to comment out code for testing purposes. Whichever the case, it is good practice to include comments in your code.

In this guide, you will learn how to write comments in Python 3 and get some tips on how to write good comments. Let's get started.

What are Comments

Comments in programming are lines of text that are written within the source code to provide more information about the code. These lines of text are ignored by the interpreters and compilers which means they will not show in your programs.

Prerequisites

Before we write comments in Python,

  • Make sure you have Python 3 installed on your system. If not, check our tutorial on how to install Python 3.

Types of Comments in Python

There are three major types of comments in Python. They include Single-line, Multi-line, and In-line Comments. One additional one is the Docstrings comments. Generally, comments in Python will follow the syntax below.

# This line describes a comment in Python
To follow along, Open a python interactive shell using the python3 command then you can copy and paste from the examples below into your shell.

Single-line Comments

Single-line comments follow the syntax shown above. Anything that follows the # symbol in that line is ignored by the interpreter. Here is an example of a single-line comment in a Hello World program.

# This code prints the string `Hello World!` to the console.
print ("Hello World!")

If you run the above code, the string Hello World! prints to the console without the extra text explaining the code.

In-line Comments

Inline comments are similar to single-line comments but they are added in the same line as the code. They seem to be part of the code but they are not. Here is an example of an inline Comment.

result = num1 + num2  # Store the result in the 'result' variable

When using inline comments, try not to overuse them. Use them only to explain the reason for writing a specific code if you find the code complex.

Multi-Line Comments

On the other hand, multi-line comments have no specified syntax in Python. As a workaround, you can use single-line comment syntax for every line of comment.

Example:

# This program adds the value of two numbers
# I am using the `Hash` symbol at the start of every line for multi-line comment. 
# The result is printed in the console.

num1 = 2
num2 = 3
print (num1 + num2)

Instead of using single-line comments, you can also use the string literals without assigning them to any variable. The interpreter ignores what is inside the quotation marks. Here is an example.

Print ("Hello World")
'This is a comment It is enclosed between a string literal that is not assigned to any variable.'

Another Way is to use multiline strings for comments. Use either double quotes or single quotes thrice.

"""
This program adds the value of two numbers
I am using multiline strings for comments. 
The result is printed in the console.
"""
num1 = 2
num2 = 3
print (num1 + num2)

Docstrings

In addition to the regular comments, Python uses docstrings to document functions, classes, modules, and methods. The trick with this is to use the comments on the first line after defining the function or module. To write the comment, use triple quotes(single or double).

Example:

def calculate_area(length, width):
    """Calculates the area of a rectangle.

    Args:
        length (float): The length of the rectangle.
        width (float): The width of the rectangle.

    Returns:
        float: The area of the rectangle.

    Raises:
        ValueError: If either length or width is negative.

    Examples:
        >>> calculate_area(5, 10)
        50.0
        >>> calculate_area(3.5, 4.2)
        14.7
    """
    if length < 0 or width < 0:
        raise ValueError("Length and width must be positive.")
    print (length * width)


calculate_area(20,40)

In this example, the docstrings provide a clear summary of the function.

Tips for Writing Good Comments in Python

When writing comments in Python, here are some best practices.

  1. Write comments that are easy to understand without over-explaining or beating around the bush.
  2. For easy readability, use proper grammar and punctuation.
  3. Avoid excessive/redundant comments. You can achieve this by using descriptive names of variables functions and classes.
  4. Update the comments when the code is modified.
  5. Use comments to break down complex algorithms and logic by referring to relevant sources and formulas.

Conclusion

This article has shown the different types of comments in Python and how to use them to provide more information about your code. Commenting ensures that the code is more readable to you, your future self, and other developers who will look at your source code. This is helpful especially when collaborating with others on your projects. If you found the article helpful, please consider subscribing to Geekbits and sharing the article with interested parties.

Thank you for reading : )

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.