VS Code: How to comment out a block of Python code

Last updated on January 7, 2021 The Plumber Loading... One comment

To comment out a line of code in Python, you can add a # before that line. So how to comment out a block of code in Python? If you have worked with some other programming language like Javascript, Dart … then you will be familiar with / * * / syntax. However, you cannot do that in Python.

To comment on a block of code in Python, you will have to prefix it with # line by line. If a block of code had hundreds of lines, it would be terrible.

Solution

Fortunately, if you use Visual Studio Code, commenting a block of code is really quick and easy. All you need to do is select that code block with your mouse, then press the following key combination:

  • Ctrl + K then press Ctrl + C if you’re using Windows
  • Command + K then press Command + C if you’re on a Mac

To uncomment a block of code, use your mouse to select it and then use the key combination:

  • Ctrl + K then Ctrl + U if you’re on Windows
  • Command + K then Command + U if you’re on a Mac

A Small Trick

If you don’t like the mentioned solution above, you can use the triple-quote trick to make a block of Python code not run. This action doesn’t actually comment out anything but only converts the code between the triple-quotes to a string.

Example:

The syntax for triple quotes consists of three consecutive single or double-quotes.

Python’s triple quotes come to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.

What Next?

Hopefully, this article has made working with Python a little easier and more comfortable. If you’d like to learn more about Python, check out our Python category page for the newest tutorials and examples.

Related Articles

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Top python course training institute in hyderabad
Top python course training institute in hyderabad
3 months ago

Very useful information. Thanks for sharing

1
0
Would love your thoughts, please comment.x
()
x