Skip to content

Comments

Always make sure that comments are up-to-date with changes in the code, as comments that contradict the code are worse that no comments at all!

Comments should be written in complete sentences with the first word capitalised. Block comments generally consist of one or more paragraphs built from complete sentences ending in a full stop. You should use two spaces after a sentence-ending full stop in multi-sentence comments, except for after the final sentence.

Block comments

These apply to some or all of the code that follow them, and are indented to the same level as the code they are for. Each line starts with a hash followed by a single space #. Paragraphs inside block comments are separated by a line containing a single hash.

Correct

def quadratic(a, b, c, x):
    # Calculate the solution to a quadratic equation using the quadratic
    # formula.
    #
    # There are always two solutions to a quadratic equation, x_1 and x_2.
    x_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)
    x_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)
    return x_1, x_2

Inline comments

These should be used sparingly. Inline comments are placed on the same line as the code they describe. They should be separated from the code by at least two spaces and start with a hash and single space #.

Wrong

some_variable = quadratic(a, b, c, x) #Solves the equation for x

Correct

some_variable = quadratic(a, b, c, x)  # Solves the equation for x

Inline comments are distracting and so should not be used if they state the obvious.

Wrong

x = x + 1  # Increment x

But sometimes, this is useful:

Correct

x = x + 1  # Compensate for border