VS Code: How to comment out a block of Python code
( 39 Articles)
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 use Visual Studio Code, commenting out 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
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 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.
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.
Hopefully, this article has made working with Python a little easier and more comfortable. If you’d like to learn more about Python, take a look at the following articles:
- List, Dict, and Set Comprehensions in Python 3
- Python: Categorizing Given Words by Their First Letters
- How to Check Whether an Object is Iterable in Python 3
- Python reduce() function examples
- Tensorflow 2 – How to Print only the Value of a Tensor
- How to Create a Pandas Series from Python Lists
You can also check out our Python category page for the latest tutorials and examples.
Thanks so much I was struggling with commenting in Python cause I have a LATAM keyboard, thanks.
Very useful information. Thanks for sharing