Previous Lesson Table of Contents Next Lesson

Suppose we have the following code:

n = 15
d = 3
q = 0

while (q + 1) * d <= n:
    q += 1

r = n - q * d
print(r)

This will output:

0

How did we arrive that conclusion? If you walk through the code closely, you might realize that we are actually doing a very basic division algorithm for 15 / 3. r is the remainder that we get, which in this case is 0, since q at the end equals 5, and q * d = 5 * 3 = 15 = n.

Given that that fact isn’t obvious from the original (we could also rename our variables to more descriptive things than single letters, but we won’t focus on that for now), it would be nice to note that in the code somehow. And we can! You can create a comment with the # symbol and write whatever you want after it on the same line.

n = 15  # Dividend.
d = 3   # Divisor.
q = 0   # Quotient.

# Compute the quotient by incrementing it
# until its product with the divisor
# exceeds the dividend.
while (q + 1) * d <= n:
    q += 1

# Compute the remainder and print it out.
r = n - q * d
print(r)

Isn’t that much clearer? Not only can we immediately understand what is happening in the code, we don’t actually have to remember it i.e. if you were to read this code six months later, you would immediately understand what its purpose was when you wrote it initially, even if you forgot.

The syntax comments is relatively straightforward, but it’s the application of them in your code that takes time. Ultimately, writing good comments is more of an art because clear language, not just good grammar, is needed to make good comments.

  • Practice writing comments for the following:

    a = 5
    b = 10
    
    n = 0
    output = []
    
    for i in range(1, n + 1):
    output.append(a * i)
    
    print(output)
    

It’s best that you try to figure out what the code is doing before writing the comments. (solution).

  • Practice writing comments for the following:

    a = 1
    b = 1
    
    n = 5
    i = 1
    
    while i <= n:
    tmp = a
    
    b = a + b
    a = tmp
    
    print(a)
    

It’s best that you try to figure out what the code is doing before writing the comments. (solution).

Comments are a great way to explain code. In fact, functions have their own special explanation construct, also known as docstrings, as we will see in the next lesson.