Labour Day Special : Flat $299 off on live classes + 2 free self-paced courses! - SCHEDULE CALL

- Python Blogs -

How To Comment Out Multiple Lines In Python Like A Pro

Introduction

If you are a Python developer, you must be aware of how to comment out multiple lines in Python. Commenting enhances code readability and facilitates collaboration among team members. It’s essential for developers to debug code, provide documentation, and maintain version control.

Moreover, they remind you why you did this. Sometimes, Python comments are short comments expressed in a single line, but often it's needed to comment out multiple lines in Python. Commenting out multiple lines in Python allows participants to grab the context quickly without interrupting the usual code run process. 

This makes multiple line Python comments a preferred choice. But, if not done properly, these may create unintentional strings and errors, running the purpose of the code. As such, mastering how to comment in Python can be an exceptional skill, boosting your coding clarity and efficiency. 

Feeling Interesting? Let’s delve deeper into the topic, but before that, you can do a little warm-up through this Python tutorial for beginners.

Please be informed that “Python Comment” is a fundamental concept in programming. They are notes in your code that are ignored by the Python interpreter. Comments in your coding explain what your code does, making it easier for you and others to understand and maintain your code. 

In this article, we will learn how to comment in Python while navigating through different types of multiline comments in Python; discuss some common issues with Python comments, and conclude following the best practices for “how to comment multiple lines in Python.” Additionally, we will look briefly at other code editors and IDEs to learn the feasibility and shortcuts to comment out multiple lines, especially the VS code and Sublime Text. 

So, if this matches your quest, let’s join hands for the rest 🙂

What are Multi-Line and Single-Line Comments in Python?

Before we dive deep into understanding the effective ways to comment in Python, let’s get some basic overview of Python comments. This includes understanding what are multi-line and single-line comments in Python. 

Single and Multiple Comments

What are  Single-Line Python Comments?

Single-line Python comments are comments that occupy just one line. They are great for explaining a specific line of code or making a quick note. In Python, you make a single-line comment by placing a hash symbol (#) before your comment.

Example of Single-Line Python Comments:

# This is a single-line comment

print("Hello, world!")  # This prints a message to the screen

In the example above, the first line is a single-line comment, and the second line has a comment at the end.

Multi-Line Comments in Python:

Sometimes, single-line comments do not serve the purpose, so more than one line is needed to make the comment effective. These are called “Multi-Line comments in Python.” They are useful for explaining more complex code or making notes over several lines.

Here are a few examples of multi-line Python comments:

Example 1:

# This is a multi-line comment

# using single-line comments.

# It explains something over multiple lines.

print("Hello, world!")

Example 2:

'''

This is a multi-line comment

using triple quotes.

It can span multiple lines.

'''

print("Hello, world!")

Let’s move on to understanding how to make multi-line comments in Python in the next section.

How to Comment out Multiple Lines in Python?

There are two main ways to make multi-line comments in Python. Let's go through each method step by step.

Method 1: Using Multiple Single-Line Comments

The most straightforward way to make multi-line comments is using multiple single-line comments. You simply place a hash symbol (#) at the beginning of each line you want to comment out.

Example:

# This is the first line of a multi-line comment

# This is the second line of the comment

# This is the third line of the comment

print("Hello, world!")

In this example, the three lines with # at the beginning are all comments. This method is simple and clear.

Method 2: Using Triple Quotes

Another way to make multi-line comments is by using triple quotes (''' or """). Triple quotes are used for multi-line strings, but if you don't assign the string to a variable, it acts as a comment.

Example 1:

'''

This is a multi-line comment

using triple quotes.

It can span multiple lines.

'''

print("Hello, world!")

Example 2:

"""

This is another example of a

multi-line comment using triple quotes.

It also spans multiple lines.

"""

print("Hello, world!")

In both examples, everything between the triple quotes is ignored by Python when the code runs, making it an effective method to temporarily disable blocks of code or add lengthy explanations. 

Want to become a successful Python Developer, here’s everything you need to know in the Python career path  complete guide.

Types of Multi Line Python Comments

There are three types of multi-line comments in Python. These include:

  1. Consecutive single-line comments
  2. Multi-line string comments, and 
  3. Triple quotes multi-line c0mments

Let’s understand each type one by one, including when should these be used.

1. Consecutive Single-line Comments

This method involves writing multiple single-line comments one after another. Each line you want to comment out starts with a hash symbol (#).

Example:

# This is the first line of a multi-line comment

# This is the second line of the comment

# This is the third line of the comment

print("Hello, world!")

This is a straightforward method and can be used in all conditions.

2. Using Multiline String as a Comment

In Python, you can use a multiline string to create comments. Multiline strings are created with triple quotes (''' or """). If you don’t assign this string to a variable, Python ignores it, making it a comment.

Example1:

'''

This is a multi-line comment

using triple quotes.

It can span multiple lines.

'''

print("Hello, world!")

Example 2: 

"""

This is another example of a

multi-line comment using triple quotes.

It also spans multiple lines.

"""

print("Hello, world!")

This method is useful for writing long comments or documentation where you do not need to add hashtags again and again.

3. Using Triple Quotes to Comment Out Multiple Lines

Similar to using multiline strings, you can use triple quotes to temporarily disable a block of code. This is handy when you want to comment out multiple lines of code for testing or debugging.

Example:

"""

for i in range(10):

    print(i)

"""

print("Hello, world!")

In the example above, the Python interpreter ignores the portion inside the Triple quotes.

Using Docstrings for Multiline Comments in Python

Docstrings stand as short for documentation strings. In Python, they are a special kind of multiline string used to document modules, classes, functions, and methods. Although their primary purpose is documentation, they can also be used as multiline comments.

What Are Docstrings?

Written using triple quotes (''' or """), Docstrings are placed right after the definition of a module, class, or function. They provide a convenient way to include documentation directly in the code.

Example of a Docstring:

def example_function():

    """

    This is a docstring.

    It describes what the function does.

    You can write multiple lines here.

    """

    print("Hello, world!")

In this example, the text inside the triple quotes is a docstring that explains what example_function does. Docstrings can span multiple lines and are used by documentation tools to generate documentation for your code.

Using Docstrings as Multiline Comments

You can also use docstrings to comment out multiple lines of code, similar to multiline comments. While this is not their intended use, it can be a handy technique.

Example:

"""

This is a multiline comment using a docstring.

You can write multiple lines here.

This can be used to temporarily disable a block of code.

"""

print("Hello, world!")

When to Use Docstrings

  1. Documenting Code: Use docstrings to explain what a module, class, or function does. This makes your code easier to understand and maintain.
  2. Multiline Comments: Docstrings can be used as multiline comments to explain complex code or temporarily disable code blocks.

Let’s now understand how to comment out multiple lines in Visual Code, in the next section.

How to Comment Out Multiple Lines in Visual Studio Code

Visual Studio Code (VS Code) is a popular code editor that provides several ways to comment out multiple lines of code efficiently. There are three main methods to comment out multi-lines in (VS). These include:

  1. Using Keyboard Shortcuts
  2. Using Command Palette, and 
  3. Using Block Comment Command

Let’s understand these types one by one, considering their use in the leading operating systems in the market, primarily Windows, Linux, and Mac.

1. Using Keyboard Shortcuts

VS Code has built-in keyboard shortcuts for commenting and uncommenting lines of code. These shortcuts are different for different operating systems. Let’s take a look at shortcuts with Windows, Linux, and Mac below.

  • Windows/Linux: Select the lines you want to comment out and press Ctrl + /.
  • Mac: Select the lines you want to comment out and press Cmd + /.

Example:

Select the lines of code you want to comment out, and press Ctrl + / in Windows/Linux,  or Cmd + /  with Mac OS.

for i in range(10):

    print(i)

The selected lines will be commented out as:

# for i in range(10):

#     print(i)

Reselecting and pressing the given shortcuts will uncomment the comments.

2. Using the Command Palette

The Command Palette is a powerful feature in VS Code that lets you access various commands. You can use it to comment and uncomment lines in the codes you wrote. All you need to do is:

  1. Press Ctrl + Shift + P to open the Command Palette with Windows and Linux or Cmd + Shift + P  if using Mac.
  2. Type "Toggle Line Comment" and select it.

Example:

Select the lines of code you want to comment out and open the Command Palette to select "Toggle Line Comment".

for i in range(10):

    print(i)

The selected lines will be commented out as:

# for i in range(10):

#     print(i)

3. Using Block Comment Command

Block Comment is another command that allows commenting in VS Code. It can be useful for commenting out larger sections of code. The shortcut for block comments is different from line comments. These include: 

  • Pressing Shift + Alt + A for Windows and Linux, and
  • Shift + Option + A for Mac OS.

Example:

Select the lines of code you want to comment out and press:

  • Shift + Alt + A in Windows/Linux, or
  •  Shift + Option + A if using Mac.

for i in range(10):

    print(i)

The selected lines will be wrapped in block comment syntax as:

/*

for i in range(10):

    print(i)

*/

Moving out to commenting out multiple lines in Sublime Text, let’s see what we have next for you.

Note: Python does not have native block comments like some other languages, so VS Code uses this format as a visual aid.

How to Comment Out Multiple Lines in Sublime Text

If you are unfamiliar with Sublime Text, let us tell you that Sublime Text is a popular code editor known for its simplicity and powerful features. Commenting multiple lines is easy with a few commands laid below:

1. Use Keyboard Shortcuts

Sublime Text has built-in keyboard shortcuts for commenting and uncommenting lines of code. These shortcuts are the same across different operating systems.

  • Windows/Linux/Mac: Select the lines you want to comment out and press Ctrl + / (or Cmd + / on Mac).

2. Use the Menu

You can also use the menu options in Sublime Text to comment and uncomment lines. All you need to do is select the lines of code you want to comment out. Go to the menu at the top and follow these steps:

  • Windows/Linux: Edit > Comment > Toggle Comment
  • Mac: Edit > Comment > Toggle Comment

This will comment out the selected lines. If the lines are already commented, it will uncomment them.

3. Use the Block Comment Command

For larger sections of code, you can use the block comment command. This is particularly useful for quickly commenting out large blocks of code. The procedure is similar in all three operating systems i.e. Windows, Linux, and Mac. All you need to do is:

Select the lines and press Ctrl + Shift + / (or Cmd + Shift + / on Mac).

Ways to Use Different Shortcuts in IDEs to Comment Out Multiple Lines

Commenting out multiple lines is also a critical requirement with IDEs (Integrated Development Environment Software). Different IDEs have different shortcuts to help you comment and uncomment multiple lines of code quickly. Let’s see some common IDEs and learn about the shortcuts for commenting with each.

Visual Studio Code vs Code

Let’s get back to boosting your Python developer skills and discuss some issues with Python comments in the next section.

Issues with Comments in Python

The two most common issues when commenting out multiple lines in Python include “Unintentional String Creation,” and “Indentation Errors.” Let’s see how they occur and how can we avoid them.

1. Unintentional String Creation

In Python, triple quotes (''' or """) are used to create multiline strings. If these strings are not assigned to a variable, they are ignored by Python, which makes them useful for multiline comments. However, if you're not careful, you might unintentionally create a string that you didn't mean to.

Example of Unintentional String Creation:

"""

This is a supposed comment,

but it's actually a string.

If this string is inside a function,

it will be executed as a docstring.

"""

def example_function():

    return "Hello, world!"

In this example, the multiline comment at the top is actually a string. If placed inside a function or class, it can be interpreted as a docstring, which might confuse.

How to Avoid It:

To avoid the formation of unintentional strings, make sure you always use # for comments, especially for single-line or simple comments. Also, check when you use triple quotes for documentation versus comments.

2. Indentation Errors

Python relies heavily on indentation to define the structure of the code. Misplacing comments or improper indentation can lead to errors or unexpected behavior.

If you accidentally change the indentation of the comment or the code around it, you can introduce errors.

Example of Incorrect Indentation:

def example_function():

    print("Hello, world!")

        # This is a comment with the wrong indentation

    print("Goodbye, world!")

This will result in an IndentationError because the comment line is not aligned correctly.

How to Avoid It:

Ensure that comments follow the same indentation level as the code they describe, and use a consistent coding style to maintain readability and prevent indentation issues. This will help rule out Indentation errors. 

We have seen an incorrect example above that results in an Indentation Error. Now let’s work with the correct Python comment way:

Correct Example:

def example_function():

    print("Hello, world!")

    # This is a correctly indented comment

    print("Goodbye, world!")

As committed at the beginning of this article, let us move to some best practices for multi-line commenting in Python before we conclude.

Best Practices for Multiline Commenting in Python

1. Use # for Single-Line Comments:

  • Even when commenting multiple lines, it's often clearer to use multiple single-line comments with #.
  • This helps prevent unintentional string creation and maintains consistency.

Here’s an ideal example:

  • # This is a multi-line comment# using single-line comments.
  • # Each line starts with a hash symbol.

2. Use Docstrings for Documentation:

  • Use triple quotes (''' or """) for docstrings to document modules, classes, and functions.
  • Docstrings should describe the purpose, inputs, and outputs of your code.

Example:

def example_function(param1, param2):

    """

    This function does something useful.

    Parameters:

   param1 (int): The first parameter.

     param2 (str): The second parameter.

     Returns:

     bool: The return value. True for success, False otherwise.

    """

    # Function implementation here

     return True

3. Be Clear and Concise:

  • Comments should be clear, concise, and to the point.
  • Avoid redundant comments that simply restate what the code does.

Example:

# Calculate the factorial of a number

def factorial(n):

    """

    Calculate the factorial of a given number.

     Parameters:

    n (int): The number to calculate the factorial for.

   Returns:

    int: The factorial of the number.

    """

    if n == 0:

        return 1

    else:

        return n * factorial(n-1)

4. Use Inline Comments Sparingly:

  • Inline comments (comments at the end of a line of code) should be used sparingly and only when necessary to explain a complex or non-obvious part of the code.

Example:
x = 10  # Initialize the variable x with the value 10

y = x * 2  # Double the value of x and store it in y

5. Maintain Proper Indentation:

  • Ensure that comments follow the same indentation level as the code they describe.
  • This helps to maintain the structure and readability of the code.

Example:

def example_function():

    print("Hello, world!")

    # This comment is properly indented

    print("Goodbye, world!")

6. Update Comments as Code Changes:

  • Keep comments up-to-date with changes in the code. Outdated comments can be misleading and confusing.
  • Regularly review and revise comments to ensure they accurately reflect the code.

Example:
# Old comment: This function prints a greeting.

# New comment: This function prints a farewell.

def example_function():

    print("Goodbye, world!")

7. Use Comment Blocks for Large Sections:

  • For large sections of code that need to be commented out, use comment blocks with # or triple quotes.
  • Indicate the beginning and end of the comment section.

Example:

# Start of commented section

# for i in range(10):

#     print(i)

# End of commented section

A Quick Review: Tips

A quick Review Tips

Conclusion

Python comments can help maintain c​lean​​ c​od​e, especially multi-line comments that describe elaborately the purpose of code.  When we comment in Python, it​​​​’s not j​u​st​ abou​t disablin​​​​​​g par​t​s temporarily; it​​​​'s al​s​o f​or​​​ clarit​​​​y an​​d​ f​u​t​u​r​e r​ef​er​enc​e. Pyt​hon​​​​​​ lac​ks​ a b​uil​t-in​​​​​​ multi-lin​​​​​​e comm​ent feat​​ure l​ike JavaScr​ip​t​ or​​​​​​​​​​ C++.
As such, learning how to comment out multiple lines in Python can be helpful along with other list of python tools

 For​​​​​​​​​​​​​​​ exam​pl​e, leavin​​​​​​g n​otes via Docstrin​​​​​​gs c​an​​ ex​p​l​ain​​​​​​​ complicated l​ogic​ b​l​ocks wit​​​​​hou​t​ aff​ec​tin​​​​​​g t​he ru​n​tim​e. This​​​​​​​​​​​​ m​et​hod​ m​ight​ feel​ uncon​​​​​​vention​​​​​​al bu​t​ wor​​​​​​​​​​ks well​ in​​​​​​ practice.

Python comments can bridge the gap between what your code does and why it does it, which is important when working in teams or revisiting your code after some time.

With the given guidelines and best practices, we believe you found this article helpful in boosting your coding efficiency. Enroll in our industry-relevant online Python training to take your skills to the next level. Let’s team up to unlock your winning career. Happy Coding!

FAQs

1. What is the purpose of Python Comments?

Python comments are used to explain and document the codes. They make your code more understandable for others and for yourself when you revisit it after some time. Python comments can describe the purpose of a function, the logic behind a piece of code, or any other information that helps clarify what the code does.

2.  How to comment multiple lines in Python?

You can write multiple-line Python comments.  The most common way is to use consecutive single-line comments with # for each line. Alternatively, you can use triple quotes (''' or """) to create a multiline string that acts as a comment if it's not assigned to a variable.

3. What are docstrings and how are they different from comments?

Docstrings are special types of comments used to document modules, classes, and functions in Python. They are written using triple quotes (''' or """) and provide a convenient way to associate documentation with Python code. Unlike regular comments, docstrings can be accessed programmatically using the __doc__ attribute.

4. What are common mistakes to avoid when writing Python comments?

Common mistakes to avoid when writing Python comments include:

  • Creating unintended strings: Using triple quotes for comments can accidentally create a string. Use # for simple comments.
  • Incorrect indentation: Ensure comments follow the same indentation level as the code they describe to avoid syntax errors.
  • Outdated comments: Keep comments updated to reflect changes in the code.
  • Over-commenting: Avoid redundant comments that state the obvious. Focus on explaining the why, not the what.


     user

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

salesforce

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
salesforce

Upcoming Class

13 days 21 Sep 2024

salesforce

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
salesforce

Upcoming Class

5 days 13 Sep 2024

salesforce

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
salesforce

Upcoming Class

4 days 12 Sep 2024

salesforce

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
salesforce

Upcoming Class

5 days 13 Sep 2024

salesforce

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
salesforce

Upcoming Class

12 days 20 Sep 2024

salesforce

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
salesforce

Upcoming Class

5 days 13 Sep 2024

salesforce

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
salesforce

Upcoming Class

2 days 10 Sep 2024

salesforce

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
salesforce

Upcoming Class

5 days 13 Sep 2024

salesforce

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
salesforce

Upcoming Class

20 days 28 Sep 2024

salesforce

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
salesforce

Upcoming Class

13 days 21 Sep 2024

salesforce

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
salesforce

Upcoming Class

26 days 04 Oct 2024

salesforce

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
salesforce

Upcoming Class

5 days 13 Sep 2024

Interviews