Skip to content
FollowtheDamnCode

Comments

Notes in your code that Python ignores.

2 minute read

Big idea

A comment is a note for humans. Python ignores everything from a # to the end of that line.

The idea

# Work out the price after a 10% discount
price = 80
print(price * 0.9)   # 72.0

The first line is a whole-line comment. The # 72.0 after the code is an inline comment — the code before it still runs.

Comments don't print — only code does
# This line is a comment. Python skips it.
print("This line runs.")
# print("This one doesn't — it's commented out.")
print("So does this one.")  # a note after code
output
This line runs.
So does this one.

Run and edit it in the app.

Watch it

Commenting out code

Putting # in front of a line of code switches it off without deleting it. Handy while you're testing:

Fix the bug: only the first greeting should print
print("Hi there!")
print("Hello again!")
output
Hi there!

Run and edit it in the app.

Multi-line notes

Python has no special multi-line comment, so you put a # on each line. You'll also see text wrapped in triple quotes:

"""
This program prints a greeting.
Written for the Python Foundations course.
"""
print("Hi")

That's really a string that isn't stored anywhere, so Python ignores it. At the very top of a file or a function it has a special name — a docstring — and it documents what the code is for. You'll write docstrings in the Functions module.

Good comments explain why

total = total * 1.18   # multiply by 1.18      ✗ says what the code already says
total = total * 1.18   # add 18% sales tax     ✓ says why

What does Python run on this line? print(5) # print(6)

Think of it like

Sticky notes on a recipe: "use the big pan — the small one overflows". The cook reads them, but they aren't steps.

Key terms

  • Comment — Text after # that Python ignores.
  • Commenting out — Adding # in front of code to switch it off.
  • Docstring — A triple-quoted string at the top of a file or function that documents it.

Check yourself

Which character starts a comment in Python?

What does Python do with a comment?

What makes a good comment?