Python Comments

Python Comments

Comments can be used to explain Python code, make the code more readable, and prevent execution when testing code.


1. Creating a Comment

Comments start with a #, and Python will ignore them.

Single-Line Comment

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

A comment can be placed at the end of a line, and Python will ignore the rest of the line.

Inline Comment

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

2. Multiline Comments

Python does not have a specific syntax for multiline comments.

To add a multiline comment, you can insert a # for each line.

Multiline Comments with #

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

Alternatively, you can use a multiline string. Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it.

Multiline Comments with Triple Quotes

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

Note: When a multiline string is the first statement in a function or module, it's known as a docstring and is used to automatically generate documentation.


Exercise

?

Which character is used to start a single-line comment in Python?