Problem Formulation
Python has two ways to comment out a block of code:
- The hashtag symbol
#
tells the Python interpreter to ignore the rest of the line. To manually commenting out a block of code by inserting a hashtag symbol in front of every line is cumbersome. - The multi-line string triple quotes
'''...'''
or"""..."""
can be inserted around a given code block. However, Python takes those triple-quote strings as docstrings.
You can see both examples here:
# Block Comment Method 1 # x = 1 # y = 2 # print(x + y)
''' Block Comment Method 2 x = 1 y = 2 print(x + y) '''
Solution Overview Table
So, how to comment out a block of Python code?
Have a look at the following table that showcases the shortcut to toggle block comments for a given selection of text:
Editor | Shortcut Block Comment | Shortcut Block Uncomment |
---|---|---|
Eclipse | CTRL + / | CTRL + / |
PyDev | CTRL + / | CTRL + / |
PyCharm | CTRL + / | CTRL + / |
Notepad++ | CTRL + K | CTRL + SHIFT + K |
IDLE | ALT + 3 | ALT + 4 |
Let’s dive into the most popular editors one-by-one.
PyCharm
PyCharm is one of the most popular Python editors. Do you want to become a PyCharm wizard and boost your coding productivity in Python? Check out our Finxter Academy course here:
*** Mastering the PyCharm IDE for Maximum Python Productivity ***
Here’s a screenshot of my PyCharm editor with some basic code:
To block-comment these three lines in PyCharm, select them with your mouse and hit CTRL + /
for a standard English keyboard layout:
This inserts the hashtag symbol in front of every selected line. In German and Swedish layouts, this doesn’t work because the / symbol can only be accessed using SHIFT + 7
, but CTRL + SHIFT + 7
is already reserved for another shortcut for “Toggle numbered Bookmark”. Therefore, you need to block-comment using the menu:
If you don’t like this menu-based approach, you can simply redefine the keyboard shortcuts as described here.
To uncomment the block, just apply the same procedure again, i.e., either by shortcut or by menu selection, applying CTRL + /
to toggle the block comment.
Notepad++
After choosing your programming language to Python, Notepad++ automatically highlights the code in the editor.
You can comment it out by selecting the lines to be block-commented and hitting CTRL + K
.
To uncomment the code block again, hit CTRL + SHIFT + K
.
IDLE
IDLE block commenting inserts two hashtag symbols ##
before each line. This differentiates it from a simple, non-block comment with only one hashtag #
.
To block-comment the selected lines in an IDLE editor, hit ALT + 3
.
To revert the block-comment and uncomment the code block, select the code block and hit ALT + 4
.
If you want to boost your Python skills, feel free to download your cheat sheets and join the free email academy here: