Coding etiquette

Coding etiquette#

So far we have been talking about writing codes that works for the computer (i.e., codes that executes smoothly without triggering an error from python). But codes need to work for human too. In particular, it is important to write codes that are readable to human.

Readable codes are important even if you are the only person who will use your codes, because you don’t know when you need to come back to it. If your code is poorly written (for the human, not for the computer per se), you will have a hard time taking off from where you left your code.

To help you develop good code hygiene / etiquette, we ask you to follow the 3 rules below:

  1. Make sure that your variable names are meaningful

  2. Format your code consistently

  3. Add comments to document your intention, as well as (less commonly) tricky implementation

Here is an example of poorly written code:

x = [1,3, 4,5, 7]
y = 9.8
z = []
for w in x:
    z.append(round(0.5 * y*w ** 2, 2))
print(z)
[4.9, 44.1, 78.4, 122.5, 240.1]

There is no documentation, and the variable names are not self-evident. Moreover, spaces between syntactical elements are inconsistent.

A cleaned up version of the above codes looks like:

# time point (in second) to evaluate
time = [1, 3, 4, 5, 7]

g = 9.8 # gravitational constant (m/s^2)

# calculate the corresponding vertical displacements (m)
y = []
for t in time:
    y.append(round(0.5 * g * t**2, 2))

print(y)
[4.9, 44.1, 78.4, 122.5, 240.1]

Usually, if your variable names are well chosen, you do not need to comment very often. In long codes, you may need a comment only every 5 - 15 lines