Skip to main content

Python Comments

Python Comments

Comments are essential when writing a program because they describe what happens inside a program.

In Python, to start writing a comment you use the hash symbol # which extends to the newline character.

note

Everything that comes after # is ignored by the interpreter.

# print a string
print('Hello world')
print('Hello!') # print an other string
Hello world
Hello!

Advantages of Using Comments

The use of comments in programs makes your code more understandable. It makes the program more readable and helps you remember why certain blocks of code were written.

Comments can be used also to ignore some code while testing other blocks of code. This offers a simple way to prevent the execution of some lines.

Single-Line Comments in Python

In Python, the hash symbol # is used to write a single-line comment.

In this way the line is ignored by the Python interpreter.

# print Hello World
print('Hello world')
note

Everything that comes after # is ignored. So, you can write the above program in a single line and get the same result:

print('Hello world') # print Hello World

Multi-Line Comments in Python

Python does not provide a separate way to write multi-line comments. However, you can get around this problem by using # at the beginning of each multi-line comment line.

# This is a
# multiline
# comment
note

Each line is treated as a single comment and all are ignored by the Python interpreter.

String Literals for Multi-line Comments

The Python interpreter ignores string literals that are not assigned to a variable, so you can write a single-line comment as:

# this is a comment
'this is an unassigned string as a comment '
note

The second line of the program in the above example is a string, but it is not assigned to any variable or function. Therefore, the interpreter ignores the string.

Similarly, you can use multiline strings (triple quotes) to write multiline comments.

The quotation character can either be ' or ".

For example:

'''

I am a
multiline comment!

'''
print("Hello World")
note

Although it is not technically a multiline comment, it can be used as one.

Python docstrings

By convention, the triple quotes that appear right after the function, method or class definition are docstrings (documentation strings).

To learn more, visit Python docstrings.