Python Multiline Comments Or How To Comment Multiple Lines

If you are using Notepad++, there is a shortcut for block commenting.

In this post:

  • Python multiline comments
  • Python multiline comments "pro way"
  • Pycharm IDE/IntelliJ multiline comments

Python doesn't have multiline / block comments. For commenting more lines, you can use the # character and the IDE support:

  • Pycharm - CTRL + / - comment / uncomment
  • Eclipse - CTRL + /- comment / uncomment
  • IDLE - CTRL + ALT + 3 - comment, CTRL + ALT + 4 - uncomment
  • Notepad++ - CTRL + Q - comment / uncomment
  • vim - CTRL + Q / kbd>CTRL + V - comment / uncomment

Python multiline comments

In python there is only one symbol for comments which is #. Some languages like Java has native support for multiline comments. This is not the case for python where you can comment several lines the same way you are commenting a single line:

# This
# is
# a 
# multi-line
# comment

Python multiline comments "pro way"

Guido van Rossum (the Python creator, Python BDFL) tweeted once a "pro tip" for Python comments:

[@BSUCSClub Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)](https://twitter.com/gvanrossum/status/112670605505077248)

According to this tip you can do comments in this way:

"""line1
line2
line3"""

'''line1
line2
line3'''

Many projects and organizations are using this kind of comments when they want to comment class or file info.

Pycharm IDE/IntelliJ multiline comments

Comment lines in Pycharm

To comment several lines of code in the Pycharm IDE / IntelliJ:

  • Select the code lines
  • Menu
  • Code
  • Comment with Line Comment
    • Windows or Linux: Ctrl + /
    • Mac OS: Command + /

result:

# time.sleep(50 / 1000)           # 50 ms
# time.sleep(5)                   # 5 secs
# time.sleep(60)                  # 1 min

Uncomment lines in Pycharm

To uncomment commented lines in PyCharm you can do it by the same steps as commenting:

  • Select the code lines
  • Menu
  • Code
  • Comment with Line Comment
    • Windows or Linux: Ctrl + /
    • Mac OS: Command + /

result:

time.sleep(50 / 1000)           # 50 ms
time.sleep(5)                   # 5 secs
time.sleep(60)                  # 1 min

Note: If you try to comment mixed lines code and comments then

  • the first press Ctrl + / will comment all lines (adding the second comment symbol # # in front of the commented lines)
  • the second one Ctrl + / will uncomment all lines (only the first comment sign)

Before

# time.sleep(50 / 1000)           # 50 ms
# time.sleep(5)                   # 5 secs
time.sleep(60)                  # 1 min
time.sleep(60 * 60)             # 1 hour

After

# time.sleep(50 / 1000)           # 50 ms
# # time.sleep(5)                   # 5 secs
# time.sleep(60)                  # 1 min
# time.sleep(60 * 60)             # 1 hour

Reference

Related Article