Python

How to Make the Multiline and Block Comments in Python

Python, renowned for its readability and simplicity, strongly emphasizes the code documentation. Among the essential tools for effective documentation are multiline and block comments. This guide looks into the complexities of creating clear and precise multiline and block comments in Python. Through numerous examples, we’ll explore the syntax, best practices, and the impacts that these comments can have on code readability and collaboration.

Mastering the Multiline and Block Comments in Python

Triple-quotes, either single ”’… ”’ or double “””… “”” quotes, are commonly used in Python to construct the multiline comments. These comments are often employed to provide detailed explanations, document function purpose, or offer context within the code.

Example 1: Basic Multiline Comment
In this example, the multiline comment is enclosed between triple single quotes. Extra details regarding the code’s purpose or additional relevant details are provided in the comment. The triple quotes allow the comment to span multiple lines without affecting the code execution.

'''
It spans multiple lines and is enclosed by triple quotes.
Useful for providing extensive explanations or context.
'''

print("Hello, World!")

Example 2: Multiline Comment within a Function
Let’s do another example that demonstrates the usage of multiline comments within a Python function.

We define a function called “add_numbers” in this example which accepts two parameters: “a” and “b”. This function aims to add these two numbers and return the result. Now, let’s dissect the function and its multiline comment:

In this case, we define a function called “add_numbers” that accepts the “a” and “b” inputs. These parameters represent the numbers to be added. The function declaration is followed right away by the multiline comment. It acts as documentation which gives important details regarding the parameters, return value, and purpose of the function.

def add_numbers(a, b):
'''
This method returns the result of adding two numbers.
Parameters:
    a (int): The 1st number.
    b (int): The 2nd number.
Returns:
    int: adding a and b
'''

The function’s objective of adding two numbers and returning the result is stated in the first line. The subsequent lines under “Parameters” describe the type and purpose of each parameter (“a” and “b”), specifying that they are integers. The “Returns” section indicates that the function returns an integer, representing the sum of “a” and “b”.

result = a + b
return result

The function computes and stores the sum of {a} and {b} in the {result} variable. This result is then returned by the function.

# Example usage
sum_result = add_numbers(3, 5)
print("Sum:", sum_result)

Ultimately, “3” and “5” are used to run the function, and the outcome is kept in the “sum_result” variable. The console then displays the sum.

In summary, this example shows the importance of multiline comments in documenting the functions’ purpose, parameters, and return values. This practice enhances code readability and provides valuable insights for developers who are using or maintaining the function.

Example 3: Multiline Comment for Code Block Explanation
Let’s explore an example that demonstrates the application of multiline comments to explain a code block, focusing on the calculation of the area of a circle in Python.

The code begins with a block comment that indicates the import of the “math” library. This library is required for mathematical operations, and the comment serves as a quick reference for developers.

# Import necessary libraries,
import math

The multiline comment following the import statement introduces the function named “calculate_circle_area” which is designed to compute a circle’s area. It takes the “radius” as a parameter.

def calculate_circle_area(radius):

This multiline comment provides essential information about the purpose of the function.

'''
determines the circle's area.
Formula: A = π * r^2
Parameters:
    radius (float): the circle's radius.
Returns:
    float: The area of the circle.
'''

The first line briefly states the function’s objective of calculating the area of a circle. The area is calculated using the mathematical formula in the “Formula” section where {A} stands for area, {π} stands for the mathematical constant of pi, and {r} stands for radius. The “Parameters” section describes the expected input parameter, “radius”, specifying that it should be a floating-point number. The “Returns” section indicates that the function returns a floating-point number that represents the area of the circle.

area = math.pi * radius ** 2
return area

The area is calculated using the provided formula within the function, and the result is returned.

# Example usage
circle_radius = 4.5
area_result = calculate_circle_area(circle_radius)
print("Circle Area:", area_result)

Finally, the function is called with a specific radius value (4.5 in this case), and the calculated area is printed to the console.

Block Comments

In Python, block comments are one-line remarks that describe the certain code segments. Even if they have their uses, it’s imperative to make use of them to prevent overcrowding the code with comments.

Example 1: Basic Block Comment
This example illustrates the use of a basic block comment to explain the purpose of the code.

The code starts with a single-line block comment. Block comments in Python are typically used for brief explanations, providing a high-level overview of the following code’s purpose:

# This is a basic block comment explaining the purpose of the code below

In this example, the block comment serves as a precise explanation of the subsequent code block. It indicates that the following code is intended to perform a specific task, and the comment acts as a quick reference for developers.

The code then calculates the sum of “variable_a” and “variable_b” and stores the result in the “result” variable. Subsequently, the result is printed on the console.

variable_a = 10
variable_b = 20

When the code is executed, the output will be “Result 30”, reflecting the sum of “variable_a” and “variable_b”.

result = variable_a + variable_b
print("Result:", result)

This example illustrates the use of a block comment to precisely explain the purpose of the subsequent code block. While this example is relatively simple, block comments become particularly valuable in larger codebases or sections where a quick understanding of the code is beneficial. The comment here acts as a guide, aiding the developers in grasping the primary objective of the code without looking into the implementation details.

Example 2: Block Comment for Conditional Section
In this example, block comments explain the logic within conditional branches. This enhances the code readability, making it easier for developers to understand the purpose of each branch without looking into the details of the code.

# Check if the number is positive or negative
number = -7

if number >= 0:
    # This block comment explains the positive case
    print("The number is positive.")
else:
    # This block comment explains the negative case
    print("The number is negative.")

Example 3: Block Comment for Loop Explanation
Here, a block comment is utilized to explain the purpose of the loop. This type of comment is especially beneficial when dealing with complex loops or when additional context is needed to understand the loop’s functionality.

# Print each name as you iterate over a list of names.
name_list = ["Amir", "Basil", "Chams"]

for name in name_list:
    # Block comment explaining the iteration process
    print("Hello, " + name + "!")

Conclusion

Mastering the art of creating effective multiline and block comments in Python is a skill that significantly contributes to code readability and collaboration. By following the best practices and incorporating the comments where they are necessary, the developers can ensure that their code remains understandable and maintainable. Whether providing a context for complex functions, explaining the algorithms or specific code sections, well-created comments are essential in Python programming.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.