Why Are Comments Used?

Challenge 4-2: Comments

So, why are comments useful? Again, isn't the whole point of a computer program to be run?

Well, yes, but that's not the whole story. Comments are really useful because they provide you with a way to make notes or to remind yourself or others how certain parts of your program work. Take a look at the following example:

i = 0

output = True

while i < 100:

if i < 50 and output:

print(i * 4)

elif not output:

print("Nothing to see here")

else:

output = not output

print(i)

i += 1

Now, because you're such a programming wiz by this point, it might be easy for you to figure out what this program is doing. But imagine you don't know Python very well, or you're just coming across this code for the first time, and you can see how it might be hard to understand. This is where comments come in:

# Initialise i to zero and output to True

i = 0

output = True


# Run while i is less than 100

while i < 100:


# If i is less than 50, and output is True, print i times 4

if i < 50 and output:

print(i * 4)


# If output is False, let the user know with a message

elif not output:

print("Nothing to see here")


# Otherwise, if i is greater than 50, turn output from True to False and then print i

else:

output = not output

print(i)


# Increment i by 1 to keep the loop going

i += 1

See how having comments in the code lets you explain exactly what your program is doing, and makes it much easier to understand!