How do you comment out multiple lines in Python?
Short answer: Python has no block comment syntax, so you put # at the start of each line. You don't have to type them one by one: select the lines in your editor and press Ctrl + / (Cmd + / on macOS). Press it again to uncomment.
# print("Step 1")
# print("Step 2")
print("Step 3") # only this line runsTriple quotes (""" or ''') also hide text, but they create a string, not a comment. Use them for docstrings, not to switch off code.
Put # on each line with Ctrl + / and Python skips those lines when it runs the file.
Shortcuts to comment multiple lines in each editor
Select the lines first, then press:
| Editor | Comment / uncomment |
|---|---|
| VS Code | Ctrl + / (macOS: Cmd + /) |
| VS Code, alternative | Ctrl + K, Ctrl + C to comment and Ctrl + K, Ctrl + U to uncomment |
| PyCharm | Ctrl + / (macOS: Cmd + /) |
| Jupyter Notebook and JupyterLab | Ctrl + / (macOS: Cmd + /) |
| Spyder | Ctrl + 1 (macOS: Cmd + 1) |
| IDLE | Alt + 3 to comment and Alt + 4 to uncomment |
| Sublime Text | Ctrl + / (macOS: Cmd + /) |
| Vim | Ctrl + V, select the lines, Shift + I, type #, Esc |
All of them add # to each line. None of them insert triple quotes.
Comment multiple lines with
The # symbol turns the rest of the line into a comment. For several lines, start each one with #:
# Calculate the total price of the order.
# Prices are in dollars and already include tax.
total = 0
for price in [10, 20, 5]:
total += price
print(total) # 35This is what PEP 8, the Python style guide, recommends for block comments: each line starts with # and a single space, with the same indentation as the code it describes.
You can also add a comment at the end of a line of code. Leave at least two spaces before the #:
discount = 0.1 # 10% for new customers