In Python, there is no specific syntax for creating multiline comments like some other programming languages (e.g., C, C++, Java). Instead, Python relies on other methods to achieve similar goals. Multiline comments are typically used to provide explanations, documentation, or notes within your code.
What does this tutorial Cover?
In this tutorial, we will explore various methods for adding multi-line comments in Python, including triple-quoted strings and documentation strings. We will also provide examples and a comparison table to help you choose the most suitable method for your needs.
Understand multiline comments
Python never officially supported multiline comments through a dedicated syntax. Therefore, there was no built-in way to write multiline comments. Instead, programmers would use a variety of ad-hoc methods to write multiline comments, such as using multiple hash characters (#) or enclosing the comment within triple quotes (”’).
Must Read: How to Create Multiline Strings in Python?
Definition
A multi-line comment is a piece of text overflowing to multiple lines and written to describe what a line of code does. Similar to a one-line comment, it is for informational purposes only and does not execute.
Let’s learn about them more in the next sections. But before that, you can follow some of the benefits of adding a multiline comment in your code.
Advantages
There are several advantages to using multi-line comments in Python:
- Improve code readability: It helps to explain complex code and makes it more readable as well as easier to understand.
- Easy to document: Multi-line comments make code easier to understand, help in finding and fixing issues, and promote teamwork among programmers.
- Switch off the code: Multi-line comments let you turn off code temporarily for testing and debugging.
Read This: How to Iterate Strings in Python
Methods: Add multiline comments
There are mostly three ways to comment a block of lines in Python. Check each of them in the below section.
Method#1: Triple-Quoted Strings
One of the most common ways to write multiline comments in Python is by using triple-quoted strings. The main purpose of these strings is to render information about functions, classes, or modules. We usually call them docstrings.
Here’s how you can use triple-quoted strings to add multi-line comments:
'''
This is how I can write multiline comments in Python.
It's not a standard way, but it allows me to add
comments as long as I want.
'''
You can also use double quotes for triple-quoted strings:
"""
Can I do it differently?
Yes, you definitely can.
In this example, you can clearly see how I'm doing it.
"""
Check This: How to Split a String in Python
Method#2: Docstrings
We already mentioned Docstrings, but let’s take this in a more detailed manner.
The sole purpose of Docstrings is to document the details of a method, class, or module. They follow a certain flow and intend to provide useful data to developers writing code. And yes, you can utilize them for adding multiline comments in your Python code.
Here’s how you can use docstrings:
def sum_func(x, y):
"""
This function takes two number, x and y, and adds them.
Call it in the following manner:
result = sum_func(11, 17)
"""
return x + y
In the above example, the docstring provides information about the function’s purpose, its parameters, and how to use it. This is especially useful for creating self-explanatory code.
Method#3: Hash Character (#)
If you don’t want to use either of the methods, use the hash symbol (#) to comment. It comments out one line at a time. While this approach is less common for multi-line comments, it can be useful in certain situations:
# This is a multi-line comment created using the '#' character.
# It consists of several lines of comments.
# While not as elegant as triple-quoted strings, it gets the job done.
Also Read: Python Comment vs Multiline Comment
Quick Comparison
To help you choose the most suitable option, let’s compare the three methods for adding multiline comments in Python:
Method | Ease of Use | Readability | Documentation |
---|---|---|---|
Triple-Quoted Strings | Easy | Good | Limited |
Docstrings | Moderate | Excellent | Extensive |
Hash Character (#) | Moderate | Fair | None |
- Ease of Use: Triple-quoted strings are the most basic way to use for writing multi-line comments. Hash characters and docstrings require more manual effort.
- Readability: Docstrings are better in terms of providing detailed info. Triple-quoted strings also offer good readability but are not as refined as docstrings. A hash symbol may make the comments less easy to read or understand.
- Documentation: Docstrings are a tool for documentation. There are tools like Sphinx which extract their detail to generate documentation. Triple-quoted strings are also useful for documentation but are not counted as an official practice. Hash characters can fulfill the purpose of adding comments but not a good deal for formal documentation.
Check Out: Several Python Exercises to Practice Python
Examples: Multiline comments in Python
Let’s check out a few more dedicated examples.
- Triple-Quoted Strings Example:
'''
This function measures the area of a rect.
You need to provide the length and width as arguments.
Use it like this:
area = calc_area(11, 17)
'''
def calc_area(len, wid):
return len * wid
- Docstrings Example:
def divide(dividend, divisor):
"""
This function divides the 'dividend' by the 'divisor' and returns the result.
Parameters:
dividend (int or float): The number to be divided.
divisor (int or float): The number by which the dividend is divided.
Returns:
float: The result of the division.
Example:
result = divide(10, 2)
"""
if divisor == 0:
raise ValueError("Division by zero is not allowed.")
return dividend / divisor
- Hash Character (#) for Each Line Example:
# The following code shows how to use a custom sorting algo.
# This algorithm has a time complexity of O(n^2)
def cust_sort(arr):
# The outer loop iterates through each ele of the list.
for i in range(len(arr)):
# The inner loop compares the current ele with the rest of the list.
for j in range(i + 1, len(arr)):
# If the current element is greater, swap them.
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
Now, it is up to you to choose the method that best fits your needs, coding standards, and the level of doc needed for your code.
Also Check: How to Print Patterns in Python
Before You Leave
While you create large Python programs, it becomes a necessity to add useful comments. After reading the above tutorial, you should be easily able to do it. Here’s a summary to help you make an informed decision:
You should always keep in mind that writing clear and concise comments is always useful. The other guys working on the same project later would find it easy to manage. If they have a task to extend the code, they must know what it is doing. The comments make you achieve this.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Facebook) if you gained some knowledge from this tutorial.
Enjoy coding,
TechBeamers.