Python Comments
Python comments are notes inside your code that the interpreter ignores. They explain why the code does something, help other people (and future you) understand it, and let you switch off lines while testing.
Single-Line Comments
A comment starts with the hash sign #. Everything after it on that line is ignored. A comment can sit on its own line or at the end of a line of code.
# Calculate the price after a discount
price = 200
discount = 0.15 # 15 percent off
print(price - price * discount)170.0
Commenting Out Code
Putting # in front of a line of code stops it from running. This is useful when you are hunting for a bug or trying an alternative.
print("Step 1")
# print("Step 2 is disabled for now")
print("Step 3")Step 1 Step 3
Python Multiline Comments
Python has no special syntax for multiline comments. The usual way is to start each line with #. Most editors do this for you: select the lines and press Ctrl+/ (Cmd+/ on macOS).
# This program converts kilometres to miles.
# One kilometre is about 0.621371 miles.
# The result is rounded to 2 decimal places.
km = 42.195
print(round(km * 0.621371, 2))26.22
You may also see a triple-quoted string used as a multiline comment. A string that is not assigned to anything is simply ignored, so it behaves like a comment. It works, but # comments are the recommended style.
Docstrings
A docstring is a triple-quoted string placed as the first line of a function, class or module. Unlike a normal comment, Python keeps it, and tools such as help() and code editors display it as documentation.
def area(width, height):
"""Return the area of a rectangle."""
return width * height
print(area(4, 5))
print(area.__doc__)20 Return the area of a rectangle.
Tips for Good Comments
- Explain why the code exists, not what each obvious line does
- Keep comments up to date when you change the code
- Put a space after the # sign, as in # like this
- Use docstrings to document every function and class you share with others
Frequently asked questions
How do you write a multiline comment in Python?
Start each line with a # sign. Editors can add them for you with Ctrl+/. A triple-quoted string also works as a block comment but is normally reserved for docstrings.
What is the difference between a comment and a docstring?
A comment starting with # is thrown away by Python. A docstring is a string stored on the function, class or module and can be read at runtime with help() or the __doc__ attribute.
Do comments slow down Python code?
No. Comments are removed when Python reads the file, so they have no effect on speed.