Python Single and Multi-Line Comments with Shortcuts

In Python (or any other programming language), comments are used to explain the source code. Comments describe the code, which helps in maintaining the application in the future for ourselves and others.

In Python, comments come in two primary forms: single-line comments and multiple-line comments. Let us learn in detail.

# single line comment using hash character
print(2 + 2)

print(2 + 3)	# another single-line comment

"multi-line comments
are
written within double quotes"

print(2 + 2)

1. Single-Line Comments in Python

Single-line comments in Python begin with a # (hash) symbol and continue until the end of the line. When executing the program, Python ignores everything after the # symbol on a line. Single-line comments are ideal for adding brief explanations or notes to specific lines of code.

Here’s an example of a single-line comment in Python:

# This is a single-line comment
x = 10  # Assigning the value 10 to the variable x

2. Multi-line Comments in Python

Python does not provide a built-in syntax for traditional block comments (such as Java comments). However, developers often use multi-line strings enclosed in triple quotes (single or double) as a workaround to create multiple-line comments.

While these are not officially the comments, these docstrings serve the purpose of providing explanations for larger blocks of code. Python ignores string literals that are not assigned to any variable, and so it will not affect the program execution.

'''
This is a multi-line comment.
It provides detailed explanations or documentation
for a block of code or function.
'''
def some_function():
    # Code for the function
    pass

Otherwise, we can use the # character to write multi-line comments as well.

# This is a multi-line comment.
# It provides detailed explanations or documentation
# for a block of code or function.

def some_function():
    # Code for the function
    pass

3. Commenting Shortcuts

Python also offers some convenient shortcuts for commenting code. These shortcuts are helpful when we want to temporarily disable or comment out a block of code during debugging or testing:

We can comment out multiple lines of code by selecting them and then pressing Ctrl + / (on Windows/Linux) or Cmd + / (on macOS) in many popular code editors and IDEs.

This action inserts # symbols at the beginning of each selected line, effectively commenting them out. Repeating the same shortcut uncommented the lines.

Ctrl + /  # Windows and Linux

Cmd + / # MacOS

Drop me your questions related to writing comments in Python.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode