CodeMIRAI
0 XP

Comments

2 min read 4 runnable examples Quiz included

A comment is text in your code that Python ignores. Comments are for people: your teammates, and you in six months.

Single-line comments

Everything after a # on a line is a comment.

Python
# Work out the price including tax
price = 100
tax_rate = 0.18          # 18% GST
total = price * (1 + tax_rate)
print(total)

A comment can sit on its own line or at the end of a line of code.

Commenting out code

Putting # in front of a line is a quick way to switch it off while you experiment:

Python
print("This runs")
# print("This does not")
print("This runs too")

Docstrings

A string written as the first line inside a function (or file, or class) is a docstring. It documents what the code does, and Python keeps it, so tools and help() can show it.

Python
def area(width, height):
    """Return the area of a rectangle."""
    return width * height

print(area(3, 4))
print(area.__doc__)

Docstrings use triple quotes """, which also let a string span several lines.

Good comments explain why

Code already says what it does. The best comments explain things the code cannot:

Python
count = 0

# Bad: repeats what the code already says
count = count + 1   # add one to count

# Good: explains a decision the code cannot
retries = 3   # the payment API sometimes fails once; three tries covers it
print(count, retries)

Name things clearly and you will need fewer comments: seconds_per_day = 86400 explains itself.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.