Writing multiline comment in Python is easy if you know the tricks. Here are some of the common ways to write multiline comments in Python.   

How to add multiple comment line in PythonPython is a beginner-friendly programming language with clear and readable syntax. Writing code in Python is more relaxed than in other languages. But sometimes, it can feel like a labyrinth where you can get lost. This is where comments come in.    

Comments are the backbone of Python code, which makes it understandable. Python offers developers handy # single comments. But what if you need to explain more than one line? What if you have the urgency to define a large block?   

This is where the Python multiline comment comes forward as a boon for developers.    

The blog is for Python freshmen like you who are training their hands on the language and learning to get better each day. Here, we will explain a step-by-step process for writing multiline comments in Python.

 

What Is Multiline Comment In Python?   

A Python multiline comment is a block of text consisting of several lines. It is not part of the code and is used for explanation or documentation purposes.    

Unlike other languages, Python has no clear syntax for writing multiline comments. To write multiline comment in Python, you can either use # at the start of each sentence or enclose the entire block of text within triple quotes.   

Here is an example of a multi-line comment in Python.   

  1.) Using `#` for each line:   

  • # This is a multiline comment.   
  • # Each line starts with a hashtag.   
  • # Print hello world.   

   2.) Using triple quotes:   

“””   

This is another way to write a multiline comment.   

Although technically a string, it serves as a comment   

when not used in the code.   

“””   

  The first example is often understood as a single-line comment. This is because # is used in Python for writing single-line comments. However, it can also be one way to write a Python multiline comment.   

  The most preferred method is to use triple quotes to write multiline comments in Python.   

   

Why Use Python Multiline Comment?   

Developers generally use multiline comment in Python for clarification and documentation purposes.    

For example, when a piece of code is complex, the comment explains why it was written. This will help other developers working on the same piece of code understand the logic behind the code.   

Multiline comments are also used for documenting because a function module or class was used in the code at a particular place.    

Overall, it makes it easier for the team to work seamlessly on code. Plus, it becomes convenient for the developer to understand the code while revisiting it for improvements.   

 

How To Write Single Line Comments In Python?

In Python, writing single lines comments is easy. All you need to do is to add prefix (#) hash before the comments. 

For example:

# This is a single-line comment in Python

Any line that has hash symbol at the start will not be executed as code.

   

How To Do Multiline Comment in Python?   

The most feared question of Python beginners is: How do you write multiline comment in Python?   

Let’s put an end to this fear once and for all.   

To comment on a single line in Python, you have a symbol (#). A sentence starting with # is considered text and not code.   

  

Here is an Python reference for writing multiline comment:  

  

# This is a single-line comment explaining the following line of code   

x = 5 # Assigning the value 5 to the variable x   

To write a multi-line comment, you only need to use triple quotes at the start and end of the sentences or text.   

Have a look at the example below:   

  

“””   

This is a multiline comment using triple quotes.   

It’s technically a string, but when not used in code,   

it serves as a comment.   

The Python interpreter ignores this block of text.   

“””   

  Using triple quotes will indicate to the interpreter that it is not part of the code and need not be executed.   

   

Types of Multiline Comments in Python   

There are three ways in which we can write Python multiline comments. They are as follows:   

  • Consecutive single-line comment   
  • Using a multiline string as a comment   
  • Using Backslash Method   

  

1.) Multiple line comment Python using single line comment   

The first method is to use the hash symbol (#) to write various Python comments in numerous lines. You must use # at the start of each sentence. This signals the interpreter that the sentences are not part of the code and will not be executed.   

  

Example to comment out multiple lines in Python: 

  

  • # This function calculates the factorial of a number.   
  • # It uses a recursive approach where the function calls itself.   
  • # If the input number is 0 or 1, the function returns 1.   
  • # Otherwise, it multiplies the number by the factorial of the number minus one.   

def factorial(n):   

if n == 0 or n == 1:   

return 1   

else:   

return n * factorial (n – 1)   

  

Here, sentences starting with # are comments. These comments explain the purpose of the factorial.   

  

2.) Python multiline comment using multi-string as a comment   

Unlike the first method, where you used the # symbol at the beginning of each sentence, you use triple quotes to enclose the entire text here.   

Please note that there shouldn’t be any space between each quote.   

This method is proper when the text does not fit in one sentence. It requires two to three sentences to be readable.    

Example:   

  

“””   

This function calculates the sum of all numbers in a list.   

It iterates through each element in the list,   

adds the element to the total and returns the sum.   

This approach ensures that all numbers are accounted for.   

“””   

   

def sum_of_list(numbers):   

total = 0   

for number in numbers:   

total += number   

return total   

  

Here, the entire comment is included in the triple quotes. Although this is technically a string, it acts as a comment when not assigned to a variable or used in any operation. The Python interpreter ignores this block of text.   

  

3.) Multiline comment Python using the backslash method   

Another typical method to write multiline comments in Python is using backslash.    

Here, instead of using the symbol at the start of the sentence, you have to use the “/” symbol at the end of each sentence. The “/” acts as a line continuation character. This instructs the interpreter that the comment is extended to the following line.    

  Backslash is usually a very unpopular method for multiline commenting in Python. Only developers use it to break comments into multiple lines and enhance their readability.   

  

Example:   

  • # This is a long comment that continues the next line \   
  • # using a backslash to indicate that the comment is not yet complete. \   
  • # The backslash allows you to split a single long comment into multilines.   

  In this example, you can see that backslash is used to break a single comment into multiple lines while instructing the interpreter to read it as a single continuous comment.   

   

What is Docstrings in Python   

New developers often need clarification on multiple line comment in Python and docstrings. Docstrings are also written within triple quotes, similar to multiline comments.   

  However, the docstrings differ from comments because they are written. Docstrings are strings of text describing the purpose of a class, module, or function in code. These are used in the code for documentation purposes only.    

  Unlike regular comments, docstrings are accessible at runtime via the __doc__ attribute, making them useful for generating documentation and providing help to users of your code.   

  

Places where Docstrings are used:   

  1. Module Docstrings: Placed at the top of a module to describe its purpose and contents.   

  

“””   

This module provides utility functions for data processing.   

It includes functions for data cleaning, transformation, and validation.   

“””   

  1. Class Docstrings: Placed immediately after the class definition to describe the class and its attributes.   

  

class Car:   

  

“””   

The Car class represents a vehicle with a make, model, and year.        

Attributes:   

make (str): The manufacturer of the car.   

model (str): The model of the car.   

year (int): The year the car was manufactured.   

“””   

  def __init__(self, make, model, year):   

self.make = make   

self.model = model   

self.year = year   

  

  1. Function/Method Docstrings: Placed immediately after the function or method definition to describe what it does, its parameters, return value, and any exceptions it might raise.   

  

def add(a, b):   

“””   

Adds two numbers together.   

   

Parameters:   

a (int, float): The first number.   

b (int, float): The second number.   

   

Returns:   

int, float: The sum of the two numbers.   

“””   

return a + b   

  

Best Practices for Multiline Commenting in Python   

Some of the best practices to write multiline comment Python are:   

  • Always ensure that the comments you write are descriptive in nature. This means that the comments clearly explain why the code is written and what the purpose of the code is in that place. Instead of describing what the code is for, talk about the goal the code fulfills.   
  • Experienced developers recommend using the “#” method to write a Python multiline comment. This method makes the comments clear, organized, and easy to understand.   
  • Always use triple quotes for docstrings while commenting out code. Docstrings are special multi line comments used to explain a function, module, or class’s purpose in code. They are usually used for documentation.   
  • Remember to update the multiline comment in Python as you update the code. Outdated comments on revised codes can create misunderstandings for other team members to follow.   
  • Don’t get carried away by the need to explain each line of code. Write multiple line comment in Python only when and where they’re needed.   
  • Stick to one commenting style throughout the code. Use either “#” or triple quotes format. Choose the one that best suits the code’s purpose.   

  

By following these practices, you ensure that the comments you write are readable and maintainable by others working on the same project.    

   

Conclusion   

There are several ways to write a Python multiline comment. The most common use is the “#” symbol or triple quotes. Always make sure that the comment summarizes the intent and purpose of the code. Also, do not clutter your code with comments.    

Comments in Python code enable developers to collaborate and work seamlessly on code. It also allows the developers to understand the purpose and approach of the code to ensure its credibility and identify scopes for improvement. 

Video Counselling