Python Comments
Comments are notes for humans. Python ignores them completely when it runs your program. Good comments explain why the code does something; the code itself already shows what it does.
Single-line comments
A comment starts with # and runs to the end of the line:
# Calculate the area of a rectangle
width = 8
height = 5
print(width * height)40
Inline comments
A comment can also follow code on the same line. Style guides recommend at least two spaces before the #:
speed = 90 # km/h
hours = 2.5 # time spent driving
print(speed * hours) # distance in km225.0
Commenting out code
Putting # in front of a line is a quick way to disable it while testing, without deleting it:
print("Step 1")
# print("Step 2 - temporarily disabled")
print("Step 3")Step 1
Step 3
Multi-line comments
Python has no special syntax for block comments. The usual approach is simply to start every line with #:
# This function will eventually talk to the payment API.
# For now it only validates the amount, because the API
# credentials are not available in the test environment.You will also see triple-quoted strings used as comments. A string that is not assigned to anything is evaluated and thrown away, so it has no effect:
"""
This text is a string literal that nobody uses,
so Python just ignores it.
"""
print("The string above did nothing.")The string above did nothing.
Docstrings
When a triple-quoted string is the first statement inside a function, class or module, it becomes a docstring. Unlike a comment, a docstring is kept at runtime and tools such as help() and editors display it.
def to_celsius(fahrenheit):
"""Convert a temperature from Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5 / 9
print(to_celsius(212))
print(to_celsius.__doc__)100.0
Convert a temperature from Fahrenheit to Celsius.
Comment or docstring?
| Use | When |
|---|---|
# comment |
Explaining a tricky line, a decision, a TODO |
"""docstring""" |
Describing what a function, class or module does for its users |
Tip: Avoid comments that repeat the code, such as
x = x + 1 # add one to x. Prefer clear variable names, and save comments for intent and surprises.
Test yourself
Which character starts a comment in Python?
- //
- #
- --
- /*
What is a docstring?
- A comment that starts with ##
- A triple-quoted string that is the first statement of a function, class or module
- Any string printed with print()
- A special file of documentation