How to Write Comments in Python (Single-line, Multi-line, Shortcuts & Indentation Tips)
Hello, this is BlockDMask.
Today, we’re going to learn how to write comments in Python.
Python supports both single-line and multi-line comments. You can freely use them depending on the situation.
Did you know that some Python comments require proper indentation?
I once struggled with PyCharm due to indentation issues in comments, so I’m writing this post to help you avoid the same mistake.
1. Types of Comments in Python
▶ Single-line Comment: #
Single-line comments start with the #
symbol.
Example 1 - Comment on an empty line
# This is a single-line comment example 1
def comment_example():
print("Comment example. DMask")
Typically, one space is added after the #
symbol before writing the comment.
Example 2 - Comment at the end of a line
def comment_example():
print("Comment example. Mask") # This is single-line comment example 2
▶ Multi-line Comment: Triple Quotes """
or '''
Multi-line comments can be written in two ways:
1) Triple double quotes """ ... """
def comment_example():
print("Comment example. Block")
"""
This is a multi-line comment.
You can freely write explanations here.
Finish by closing with triple double quotes.
"""
a = 3 # regular code 1
b = 4 # regular code 2
2) Triple single quotes ''' ... '''
while True:
'''
This program performs certain operations.
Please mention the source when sharing.
Additional explanations go here.
'''
print("=" * 30)
2. Comment Shortcuts (PyCharm, IDLE, VSCode, etc.)
Using shortcuts makes it easy to add or remove comments. Most editors use similar shortcut keys.
▶ Common shortcuts for PyCharm, VSCode, and most IDEs
- Windows:
CTRL + /
- Mac OS:
Command + /
▶ Python IDLE shortcuts
- Add comment:
ALT + 3
- Remove comment:
ALT + 4
▶ Multi-line comment example using shortcut
Select multiple lines and apply the shortcut to comment or uncomment them.
Original Code:
def add_numbers(a, b):
print(f"{a} + {b} = {a + b}")
x = 10
y = 20
add_numbers(x, y)
After Applying Shortcut:
# def add_numbers(a, b):
# print(f"{a} + {b} = {a + b}")
#
# x = 10
# y = 20
# add_numbers(x, y)
3. Important: Indentation in Python Comments
Unlike languages like C, C++, or C#, Python is sensitive to indentation — even for comments.
▶ Indentation error example
class CommentExample:
'''
Python comments must be properly indented. This will cause an error.
'''
def __init__(self):
a = 10
b = 20
Error: IndentationError: expected an indented block
▶ Correct indentation example
class CommentExample:
'''
Python comments must be properly indented.
'''
def __init__(self):
a = 10
b = 20
That’s it for today’s post about Python comments.
Thank you for reading!
Comments
Post a Comment