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

Updated: September 3, 2023 By: Napoleon 2 comments

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 the / * * / syntax. However, it is impossible to 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. Fortunately, if you’re using VS Code (Visual Studio Code), commenting out a block of code is really quick and easy.

Solution

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

You can also use the following:

  • Ctrl + / (the slash key) to comment and uncomment lines of Python code on Windows.
  • Command + / to comment and uncomment multiple lines of Python code on Mac.

A quick demo is worth more than a thousand words:

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 (and therefore it won’t affect other code).

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 can help you a little bit when working with VS Code. If you want to explore more tips and tricks related to this code editor, take a look at the following articles:

You can also check out our Visual Studio Code topic page for more tips and tricks to improve your producibility and coding experience.

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
Emmanuel
Emmanuel
2 years ago

Thanks so much I was struggling with commenting in Python cause I have a LATAM keyboard, thanks.

Top python course training institute in hyderabad
Top python course training institute in hyderabad
2 years ago

Very useful information. Thanks for sharing

Related Articles