You may have noticed that I sometimes write words in the code that don’t affect execution at all. These are known as comments and are very useful in describing what a bit of code does or why it is there. A comment in Python can be one of two things: any words on a line after a
# (hash); or any multi-line string (a string with 3 quotes instead of one).
If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!
The main difference between a hash (#) comment and a string comment is that a string comment is mainly used at the top of a function and a hash comment is used everywhere else. For example, here’s a good example of a string comment and a hash comment:
def estimate_circumference(radius): """Estimates the circumference of a circle from its radius. Circumference = 2 * pi * radius """ two_pi = 6.28 # pi is about 3.14, this is 2 * pi return two_pi * radius
The first comment explains exactly what the function does; while the second comment explains why
two_pi is there. Without these comments, it may not be clear to the next programmer (or, more often, future you) what is going on in this function.
You must watch out for bad comments, however. There are two kinds: Those that don’t tell you anything and those that tell you the wrong thing. The former is more annoying than hurtful:
def adder(x, y): value = x + y return value # This returns value.
This comment is completely unnecessary, and only clutters the code. Only use comments when you need to further clarify something or explain code that is difficult to understand.
Much worse is a comment that is wrong in part or entirely. This usually happens when commented code gets edited, but the editor doesn’t change the comments to match!
def add_tax(sub_total, tax_rate): tax_amount = sub_total * tax_rate # This removes the California tax rate. total = tax_amount + sub_total return total
“What? There is nothing here that removes the California tax rate. California isn’t even in this code! Should I add it? What’s going on!?” — Future Programmer
This is a simple function with a poor comment that makes it much more confusing. Because the author didn’t update the comment when removing code about the California tax rate, the comment is now not only useless, it’s distracting and confusing.
Remember to use string comments at the beginning of a function to explain what it does, and hash comments to clarify what some code means. The easier the code is to read, the easier the code is to fix!