Python Comments

Comments are notes inside your code that Python ignores, letting you explain what your program does or temporarily disable lines.

Why write comments?

A comment is text that the interpreter skips over completely. It has no effect on how your program runs. Comments exist for the humans reading the code, including your future self, to explain intent, clarify a tricky step, or leave a reminder. Well-placed comments make code far easier to understand and maintain.

Single-line comments

A comment starts with a hash symbol (#). Everything from the # to the end of that line is ignored by Python. You can put a comment on its own line or add it to the end of a line of code.

Example

# This is a comment on its own line
print("Hello, World!")  # This comment follows some code

Using comments to disable code

Because Python ignores commented lines, adding a # in front of a statement is a quick way to stop it from running without deleting it. This is handy when you are testing which parts of a program cause a certain result.

Example

# print("This line will not run")
print("But this line will")

Multi-line comments

Python has no dedicated syntax for a block comment that spans many lines. The straightforward approach is simply to begin each line with its own # symbol.

Example

# This explanation is long,
# so it is spread across
# several separate comment lines.
print("Done")

Some people take advantage of a trick: a string that is not assigned to anything is allowed to sit on its own, so a triple-quoted string can act like a comment. Strictly speaking Python still reads it as a string, but since nothing uses the value it is effectively ignored.

Example

"""
This triple-quoted text is not assigned to a variable,
so it behaves much like a multi-line comment.
"""
print("Finished")
Note: Aim to explain why the code does something, not just what it does. The code itself already shows the what; a good comment adds the reasoning that is not obvious at a glance.

Exercise: Python Comments

Which symbol starts a single-line comment in Python?