Python provides the ability to comment out multiple lines for different purposes. The comment sign or hash mark can be used to comment out multiple lines. Commenting out multiple lines may be useful for testing and debugging code by printing to the console and then commenting out for later use. In this tutorial, we examine how to comment out multiple lines using the hash mark (#) and string literal in Python.
Comment Out Multiple Lines Using Hash Mark
The hash mark can be used to comment out multiple Python statements, code, and lines. The hash mark is added at the start of every line we want to comment out. In the following example, we comment on the print() statements that are used for debugging and troubleshooting purposes. The first code example shows the normal usage without comment out.
a = 10
print(a)
print(a*a)
result = 2*a
Now we comment out multiple lines or code blocks consist of print() statement. Now the print() statements do not interpreter by Python interpreter and do not print related values to the standard output.
a = 10
#print(a)
#print(a*a)
result = 2*a
Comment Out Multiple Lines Using String Literal
Python provides the string literals or multiline string in order to create string values and variables. If the specified string literal is not assigned into a variable it is uneffective and stays like a comment. The multiline string literal can be used to comment out multi line comment out. But keep in mind that the if the commented out Python statements and code contains string it may create errors and using multi line string literal is not recommended for these cases. First we see the uncommented code like below.
a = 10
print(a)
print(a*a)
result = 2*a
In the following example we comment out the print() statements by using multiline string literals. Triple quotes are used to comment out multiline in this case.
a = 10
'''
print(a)
print(a*a)
'''
result = 2*a