Comments in Python
Learn what comments are, how to write them, and why writing good comments makes you a better programmer.
Notes that Python skips
Python reads and runs every line of your code. A comment is a note it skips completely. It is only there for humans. Beginners often skip comments, but they are one of the best habits to build, especially when you return to code you wrote weeks ago and cannot remember what it does.
A comment starts with #. Everything after it on that line is ignored. It can sit on its own line or at the end of a line of code.
# This is a comment. Python will not run this line.
print("Hello") # This part runs. This after # is ignored.
# print("This line will NOT run because it starts with #")
Hello
Only one line of output appears. The first and third lines are pure comments, and on the middle line the text after # is thrown away. A common style tip is to leave two spaces before a comment that sits at the end of a line, and one space after the #.
Comments change nothing
These two programs behave exactly the same:
# Program 1, with comments
# Ask the user for their name
name = input("Enter your name: ")
# Greet the user
print("Hello, " + name + "!")
# Program 2, without comments
name = input("Enter your name: ")
print("Hello, " + name + "!")
Comments never change how a program works. They are just helpful notes. That also means you can add or remove them as often as you like without any risk of breaking something.
One thing to remember: a # inside quotes is not a comment, it is just a character in the text.
print("Use # to start a comment") # the # inside the quotes is printed
Use # to start a comment
Longer notes and docstrings
Python has no special symbol for multi-line comments. The simple way is a # at the start of each line:
# This program calculates the area of a rectangle.
# It asks the user for the length and width,
# then multiplies them and prints the result.
length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = length * width
print(f"Area: {area}")
There is another way to write longer notes, using triple quotes. These are called docstrings, and they describe what a function does. Python does not run them as code.
def calculate_area(length, width):
"""
This function calculates the area of a rectangle.
It takes two arguments: length and width.
It returns the area as a number.
"""
return length * width
The text between the triple quotes is the docstring. It goes on the first line inside the function. Editors can read docstrings and show them as help text when you use the function. You can even print one yourself:
print(calculate_area.__doc__)
Do not worry about the def line yet. Functions get their own lesson. For now just remember that # is for notes inside code and triple quotes are for describing a function.
Commenting out code
Put a # in front of a line to switch it off for now. This is called commenting out, and it is handy when testing:
name = "Alice"
print("Hello, " + name)
# print("This line is disabled for now.")
print("Goodbye, " + name)
Hello, Alice
Goodbye, Alice
The middle print does not run. Remove the # later to bring it back, which beats deleting and retyping.
Imagine a program is giving a wrong answer. You can comment out lines one by one and run it again to find which line causes the problem. Programmers do this all the time to track down bugs.
Most editors let you do this quickly. In VS Code, select the lines and press Ctrl + / on Windows or Cmd + / on Mac. Press it again to switch the lines back on.
When should you comment?
Should you comment every line? No. Too many comments are as bad as too few. Here is a simple guide:
- Do comment complex logic that is not obvious, anything that makes someone wonder why it works
- Do comment the purpose of a function or a block of code
- Do comment anything unusual: if you did something in a strange way, say why
- Do not comment the obvious. Writing
# print the nameaboveprint(name)adds nothing.
# Bad comment: states the obvious
age = 25 # set age to 25
# Good comment: explains the reason
age = 25 # default age used when no profile data is available
Good comments explain why, not what. The code already shows what it does. A comment is most useful for the reason behind it.
Useful comment habits
- Start a file with a short header. Say what the program does and who wrote it.
- Mark unfinished work. Programmers write
# TODO: add error handlingso they can search for TODO later. - Mark known problems.
# FIXME: crashes when the list is emptytells the next reader to look here. - Section off long files. Short lines like
# ---- Helper functions ----help your eyes find their place.
# calculator.py
# A small program that adds two numbers.
# TODO: let the user pick other operations
a = 4
b = 6
print(a + b)
Keep comments short and friendly. If a comment needs three paragraphs, the code is probably too complicated and should be simplified instead.
Mistakes to avoid
- Out of date comments. If you change the code, update the comment next to it. A wrong comment is worse than no comment, because it lies to the reader.
- Forgetting the
#. A note without#is not a comment, and Python will try to run it and give aSyntaxError. - Commenting out and forgetting. Do not leave big blocks of disabled code in a finished program. Delete what you no longer need.
- Hiding bad code behind comments. Better to rename a confusing variable than to explain it in a comment.
# Calculate the tax
total = price + price * 0.2 # this really adds 20% tax
# Better: a clear name needs no comment
tax_rate = 0.2
total = price + price * tax_rate
Clear code with a few well chosen comments always beats messy code with lots of them.
Key takeaways
- A comment starts with
#. Python ignores it, and it can sit on its own line or after code - Comments never change what a program does
- For several lines, start each line with
#. Triple quote docstrings describe functions - Commenting out disables a line without deleting it. Use
Ctrl + /orCmd + / - Comment the why, not the obvious what
- Keep comments up to date and use TODO and FIXME to mark work for later