How to Use Block Comments in Python

You can easily create multi-line comments in Python with ease by using quotations. The # docustring will only allow you to comment per each line. However triple quotation “””” or ”’ should easily allow you to create multiple-line comments.

Using Triple Quotes for Multi-line Python Comments

Even though triple quotes are primarily used for docstrings or multi-line strings, they can also be repurposed for block comments. Both single and double triple quotes (''' or """) can be used.

This is a block comment
spans multiple lines
using triple single quotes

Another example of a block comment
using triple double quotes.

Note: Using triple quotes as comments can sometimes be misleading, especially for someone reading the code, as their primary purpose is for multi-line strings. Make sure to clarify your intentions if you choose this method.

Functions are a way to have repeatable code. These can be complex and may need a ton of explanation. So using multiple line comments to explain how the function works is a key to collaboration and understanding.

Example of a Block Text in a Function

def clean_user_data(dataframe):
    This function cleans a dataframe containing user details.
    Steps involved:
    1. Remove any rows with missing 'name' or 'email' values.
    2. Convert all emails to lowercase for consistency.
    3. Replace any non-standard age values (e.g., negative values) with NaN.
    - dataframe (pd.DataFrame): The input dataframe with user details.
    - pd.DataFrame: The cleaned dataframe.
    # Remove rows with missing 'name' or 'email' values
    dataframe.dropna(subset=['name', 'email'], inplace=True)
    # Convert email addresses to lowercase
    dataframe['email'] = dataframe['email'].str.lower()
    # Replace non-standard age values with NaN
    dataframe.loc[dataframe['age'] < 0, 'age'] = None
    return dataframe

Using Shortcuts for IDE or Text Editors to Create Block Comments

Many Integrated Development Environments (IDEs) and text editors that support Python have built-in features to comment out multiple lines of code at once. Here are a few examples:

Jupyter notebooks: When you’re in the cell’s edit mode (actively typing into a code cell), you can use the following shortcut to toggle (add/remove) comments for selected lines:

Ctrl + / (Cmd + / on macOS)

To create a block comment use this shortcut in Jupyter Notebooks:

  1. Highlight the lines of code you want to comment out.
  2. Press Ctrl + / (or Cmd + / if you’re on macOS).
  • PyCharm: Select the lines you want to comment on and press Ctrl + / (or Cmd + / on macOS).
  • Visual Studio Code (VS Code): The same shortcut, Ctrl + / (or Cmd + / on macOS), works in VS Code.
  • Sublime Text: Use Ctrl + / or Cmd + / depending on your operating system.

Gaelim Holland

Notify of

Inline Feedbacks
View all comments