To comment out a line of code in Python, you can add a
/ * * / 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.
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).
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 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:
- VS Code: Set Preferred Quote Type for Quick Fixes
- VS Code: How to Position/Align the Bottom Panel
- VS Code: Opening Multiple Windows/Projects Simultaneously
- VS Code: Hide/Show the Debug button in package.json
- VS Code: How to Compare Two Files (Find the Difference)
- Flutter & VS Code: Auto Trigger Hot Reload on Save
You can also check out our Visual Studio Code topic page for more tips and tricks to improve your producibility and coding experience.