Python Comments

Comments can be used to explain Python code.

Comments can be used to improve code readability.

When testing code, comments can be used to prevent execution.

Create Comments

Comments start with # At the beginning, Python will ignore them:

Example

#This is a comment
print("Hello, World!")

Run Example

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

Example

print("Hello, World!") #This is a comment

Run Example

Comments do not have to be text that explains the code; they can also be used to prevent Python from executing code:

Example

#print("Hello, World!")
print("Cheers, Mate!")

Run Example

Multi-line Comments

Python actually does not have a syntax for multi-line comments.

To add multi-line comments, you can insert one for each line #:

Example

#This is a comment
#written in
#more than just one line
print("Hello, World!")

Run Example

Or, in a way that does not quite meet expectations, you can use multi-line strings.

Since Python will ignore string literals that are not assigned to variables, you can add multi-line strings (triple quotes) in the code and add comments within them:

Example

"""
This is a comment
written in 
more than just one line
"""
print("Hello, World!")

Run Example

As long as the string is not assigned to a variable, Python will read the code, then ignore it, and you have already completed multi-line comments.