Zone Of Makos

Menu icon

Comments in Python

Comments are lines of text in a Python program that are ignored by the interpreter. They are used to add notes and explanations to the code, making it easier for other programmers (or yourself, in the future) to understand what the code does.

Single-line comments

The simplest way to add a comment in Python is to use the hash (#) character. Any text after the hash character on the same line is ignored by the interpreter. For example:

# This is a single-line comment
print("Hello, World!") # This is another single-line comment

In this example, the first line is a comment that describes what the code does. The second line is a print statement that outputs the text "Hello, World!" to the screen. The third line is another comment that explains what the print statement does.

Multi-line comments

Sometimes you may want to write a longer comment that spans multiple lines. In Python, you can use triple quotes ( ''' ''' or """ """ ) to create a multi-line comment. For example:

'''
This is a multi-line comment
that spans multiple lines.
It is enclosed in triple quotes.
'''

print("Hello, World!")

In this example, the first three lines are a multi-line comment that describes what the code does. The fourth line is a print statement that outputs the text "Hello, World!" to the screen.

Commenting out code

Sometimes you may want to temporarily remove a piece of code from your program without deleting it. In Python, you can comment out code by adding a hash character (#) at the beginning of the line. For example:

print("Hello, World!")
# print("This line is commented out")
print("Goodbye, World!")

In this example, the second line is a print statement that has been commented out. When the program is run, this line is ignored by the interpreter and does not produce any output.

Conclusion

Comments are a useful tool for adding notes and explanations to your Python code. Whether you are writing single-line comments, multi-line comments, or commenting out code, make sure to use comments to make your code more understandable and maintainable.