Skip to main content
HomeTutorialsPython

How to Comment Out a Block of Code in Python

Using comments is fundamental for effectively working with Python. In this short tutorial, learn how to comment out a block of code in Python.
Jan 2024  · 3 min read

Comments are one of the most useful tools when working with Python. They guide us through the logic, decisions, and purposes behind blocks of code without interfering with the execution. Comments help make the code more readable and maintainable and facilitate collaboration in a team setting.

This tutorial will delve into two effective methods for commenting out multiple lines of code in Python, ensuring your code is well-documented and easily understandable.

Why are Block Comments in Python Important?

Comments are often one of the first concepts you encounter in your Python learning journey. They provide useful context over the intent behind a certain code snippet. They offer clarity and context over why a script behaves as it does. There are a variety of important reasons why you should always use comments in your scripts. Here are four of them:

  • Documentation: Comments act as a form of documentation explaining the purpose of functions, classes, or blocks of code. This is especially useful for complex algorithms where the logic may not be immediately apparent.
  • Readability: Well-commented code is easier to read and understand. This is crucial when you or others revisit the code after some time.
  • Debugging: Temporarily commenting out sections of code is a common practice for isolating and identifying bugs.
  • Collaboration: In a team environment, comments make code more shareable and understandable, facilitating smoother collaboration and code reviews.

Using Single-Line Block Comments in Python

Before we dive into commenting out multiple lines, let's start with the basics of single-line comments. In Python, a single-line comment begins with the hash symbol (#), and the Python interpreter ignores everything that follows it on that line. To create a single-line comment, follow the instructions below:

  1. Placement: Place the # symbol at the beginning of the line or after the code on the same line. Comments can be placed above the code they describe, on the same line to the right of the code, or standalone.
  2. Content: After the # symbol, write your comment. This can be an explanation of the line of code, a note for future reference, or any useful information related to the code.
# This is a single-line comment explaining the next line of code
print("Hello, world!")  # This prints a message to the console

Method #1: Commenting Using Multiple Single Line #

The most straightforward way to comment in Python is by using the # symbol, which comments out everything that follows it on the line. While Python does not have a specific syntax for block comments, you can use multiple # symbols to comment out each line individually. All you need to do is perform the following steps:

  1. Identify the code block: First, identify the code block you wish to comment out. This could be a function, a loop, or any segment of your code that you want to disable or explain.
  2. Comment each line: Place a # symbol at the beginning of each line you wish to comment out. This tells the Python interpreter to ignore these lines during execution.

You can see the example below:

# Example of commenting out multiple lines individually 
# def example_function(name):
#	# This function prints "Hello " and the input name
# 	print("Hello", name)

Python Block Comment Method #2: Commenting Using Triple-Quoted String Literals

An alternative method for commenting out multiple lines is to use triple-quoted string literals (''' ''' or """ """). While not officially block comments, these string literals are often used as such, especially for multi-line comments or docstrings. To use triple-quoted strings, simply place ''' or """ before and after the block of code you wish to comment out, as such:

'''
def example_function(name):
print("Hello", name)
'''

Triple-quoted string literals are most commonly used for documenting Python functions. For example:

# Create example_function()
def example_function(name):
	'''
This function takes as input a name, and returns a salutation to the name in the form of "Hello name"
	'''
	# Print the output 
print("Hello", name)

These tripled quoted string literals are called docstrings — you can read more about them in our docstrings tutorial.

Final Thoughts

Comments are an indispensable part of writing clean, maintainable, and collaborative Python code. Whether you're using single-line comments with # or multi-line comments with triple-quoted strings, the goal is to enhance the readability and understanding of your code.

For further reading and to deepen your knowledge of best practices in Python programming, check out the following resources:


Photo of Adel Nehme
Author
Adel Nehme

Adel is a Data Science educator, speaker, and Evangelist at DataCamp where he has released various courses and live training on data analysis, machine learning, and data engineering. He is passionate about spreading data skills and data literacy throughout organizations and the intersection of technology and society. He has an MSc in Data Science and Business Analytics. In his free time, you can find him hanging out with his cat Louis.

Topics

Keep Learning Python! 

Track

Python Fundamentals

15 hours hr
Grow your programmer skills. Discover how to manipulate dictionaries and DataFrames, visualize real-world data, and write your own Python functions.
See DetailsRight Arrow
Start Course
Certification available

Course

Writing Efficient Python Code

4 hr
112.3K
Learn to write efficient code that executes quickly and allocates resources skillfully to avoid unnecessary overhead.
See MoreRight Arrow
Related

Becoming Remarkable with Guy Kawasaki, Author and Chief Evangelist at Canva

Richie and Guy explore the concept of being remarkable, growth, grit and grace, the importance of experiential learning, imposter syndrome, finding your passion, how to network and find remarkable people, measuring success through benevolent impact and much more. 
Richie Cotton's photo

Richie Cotton

55 min

Python NaN: 4 Ways to Check for Missing Values in Python

Explore 4 ways to detect NaN values in Python, using NumPy and Pandas. Learn key differences between NaN and None to clean and analyze data efficiently.
Adel Nehme's photo

Adel Nehme

5 min

Seaborn Heatmaps: A Guide to Data Visualization

Learn how to create eye-catching Seaborn heatmaps
Joleen Bothma's photo

Joleen Bothma

9 min

Test-Driven Development in Python: A Beginner's Guide

Dive into test-driven development (TDD) with our comprehensive Python tutorial. Learn how to write robust tests before coding with practical examples.
Amina Edmunds's photo

Amina Edmunds

7 min

Exponents in Python: A Comprehensive Guide for Beginners

Master exponents in Python using various methods, from built-in functions to powerful libraries like NumPy, and leverage them in real-world scenarios to gain a deeper understanding.
Satyam Tripathi's photo

Satyam Tripathi

9 min

Python Linked Lists: Tutorial With Examples

Learn everything you need to know about linked lists: when to use them, their types, and implementation in Python.
Natassha Selvaraj's photo

Natassha Selvaraj

9 min

See MoreSee More