DEV Community

Paulo GP
Paulo GP

Posted on • Updated on

Python: A Guide to Comments

Introduction

Code comments are invaluable annotations that enhance code readability, facilitate collaboration, and aid in maintenance. In Python, comments play a crucial role in conveying intent, documenting functionality, and explaining complex algorithms. This chapter delves into the art of writing effective comments in Python, covering inline comments, single-line comments, and multi-line comments.

Topics

  • Inline comments: Enhancing code clarity
  • Single-line comments: Concise explanations
  • Multi-line comments: Structured documentation

Inline Comments: Enhancing Code Clarity

Inline comments are succinct annotations placed within a line of code to clarify its purpose or functionality. They provide immediate context to readers, aiding in comprehension and maintenance.

# Calculate the area of a circle
radius = 5
area = 3.14 * radius ** 2  # Formula: πr^2
print("Area of the circle:", area)
Enter fullscreen mode Exit fullscreen mode

Output:

Area of the circle: 78.5
Enter fullscreen mode Exit fullscreen mode

Single-line Comments: Concise Explanations

Single-line comments, denoted by the # symbol, are used to provide brief explanations or annotations for a single line of code. They are ideal for documenting variable assignments, function calls, or expressions.

# Initialise variables
x = 10
y = 20
# Perform addition
result = x + y  # Add x and y
print("Result:", result)
Enter fullscreen mode Exit fullscreen mode

Output:

Result: 30
Enter fullscreen mode Exit fullscreen mode

Multi-line Comments: Structured Documentation

Although Python lacks native support for multi-line comments, docstrings serve as a viable alternative for documenting modules, classes, functions, and methods. Docstrings are enclosed within triple quotes (''' or """) and are accessible via the __doc__ attribute.

def fibonacci(n: int) -> int:
    """Compute the nth Fibonacci number.

    Args:
        n (int): The index of the Fibonacci number to compute.

    Returns:
        int: The nth Fibonacci number.
    """
    if n <= 1:
        return n
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)


# Display the documentation for the fibonacci function
print(fibonacci.__doc__)
Enter fullscreen mode Exit fullscreen mode

Output:

Compute the nth Fibonacci number.

    Args:
        n (int): The index of the Fibonacci number to compute.

    Returns:
        int: The nth Fibonacci number.
Enter fullscreen mode Exit fullscreen mode

Conclusion

In Python, code comments serve as indispensable aids for understanding, maintaining, and collaborating on codebases. Whether through inline comments, single-line comments, or multi-line docstrings, the judicious use of comments elevates code quality and fosters a culture of clarity and collaboration.

Top comments (0)