Comments
Comments are notes for humans that Python ignores. Good comments explain why code does something, not what it does; the code itself should already say what.
Single line comments
A comment starts with # and runs to the end of the line.
# Calculate the area of a rectangle
width = 4
height = 7
area = width * height # a comment can also follow code
print(area)Commenting out code
Putting # in front of a line is a quick way to disable it while testing.
print("This runs")
# print("This does not")Most editors toggle comments on the selected lines with Ctrl+/ (Cmd+/ on macOS).
Multi line comments
Python has no dedicated multi line comment syntax. You either start each line with #:
# This function converts a temperature.
# Input is in Celsius, output is in Fahrenheit.
# The formula is F = C * 9/5 + 32.
def to_fahrenheit(c):
return c * 9 / 5 + 32
print(to_fahrenheit(100))or you use a string on its own that is never assigned to anything. Python evaluates it and throws it away:
"""
This is a multi line string used as a comment.
It is not assigned, so it has no effect.
"""
print("Still works")Docstrings
A string placed as the very first statement inside a function, class or module is called a docstring. Unlike a normal comment it is kept at runtime and used by help tools.
def greet(name):
"""Return a friendly greeting for the given name."""
return "Hello, " + name
print(greet("Ananya"))
print(greet.__doc__)Tools like help(greet) in the shell, editors and documentation generators all read docstrings, so use them for anything other people (including future you) will call.
Writing good comments
- Explain intent, assumptions and non-obvious decisions.
- Do not restate the code.
x = x + 1 # add one to xhelps nobody. - Keep comments up to date. A wrong comment is worse than none.
Practice
- Add a docstring to the
to_fahrenheitfunction above and print it with.__doc__. - Take any example from the previous lesson and add one comment that explains why rather than what.
