Multiline Comment in Python


Python is known for its readability. It encourages developers to add comments to their code.

Comments serve as notes to explain what's happening in the code, making it easier for others (and your future self!) to understand.

Let's dive into the world of comments, with a focus on multiline comments.

    Table of Contents

  1. Why Use Comments?
  2. Single-Line Comments
  3. MultiLine Comments
    1. Triple-Double Quotes
    2. Using # on Each Line
  4. Commenting in VS Code
  5. Docstring vs Comment
  6. Best Practices for Multiline Commenting
  7. Conclusion

Why Use Comments?

Writing comments is a sign of a good programmer and writing a good comment is an art.

Comments are used to explain what the program is doing in short. They are used to explain complex logic, document functions, or even serve as reminders for future improvements.


Single-Line Comments

Single-line comments are comments that span only one line. Generally, they are used to explain a single line of code.

To write a single-line comment, use the # symbol before the comment.

# This is a single-line comment
print("Hello, World!") # This is also a single-line comment

MultiLine Comments

Multiline comment by its name is a comment that spans multiple lines. It is used to explain a block of code or a function.

There are two ways to write multiline comments in Python.

  1. Using triple-double quotes (""")
  2. Using # on each line

1. Triple-Double Quotes

For multiline comments, Python offers a clean solution using triple-double quotes ("""). This is particularly useful for more extended explanations or docstrings.

"""
This is a multiline comment
spanning multiple lines.
It adds clarity and documentation.
"""

print("Hello, World!")

2. Using # on Each Line

Another way to write multiline comments is to use the # symbol on each line.

# This is a multiline comment
# spanning multiple lines.
# It adds clarity and documentation.

print("Hello, World!")

Commenting in VS Code

VS Code offers a convenient way to comment out multiple lines of code. Simply select the lines you want to comment out and press Ctrl + / (Windows) or Cmd + / (Mac).

Alternatively, you can use the Ctrl + K + C (Windows) or Cmd + K + C (Mac) shortcut to comment out the selected lines.

comment in vs code
Commenting in VS Code

Docstring vs Comment

Docstring:

Comment:


Best Practices for Multiline Commenting

Here are some best practices to follow when writing multiline comments.


Conclusion

In the vast Python landscape, comments are your allies. Multiline comments, whether adorned with triple-double quotes or # on each line, empower you to provide insightful explanations. Embrace comments as your code's storytellers.

Happy coding! 🚀✨