Writing good code#

Writing readable code#

Technically, python allows us to write code like this.

a=5;b=3;c=8;d=(a+b)/c;print("Yin" if d==5 else "Yang")
Yang

However, for readability, it is recommended to write individual statements in individual lines. Also put empty lines between sections and introduce comments to explain why things are done.

# initialize program
a=5
b=3
c=8

# compute result before we can evaluate it
d=(a+b)/c

If you work with Jupyter notebooks, print out intermediate results to allow the reader to see what’s happening.

d
1.0

Consider writing spaces between variables, operators and numbers, because this is easier toreadthanthat,right?

d = (a + b) / c
d
1.0

Some people are ok with such short statements:

print("Yin" if d==5 else "Yang")
Yang

Others prefer to write code out.

if d == 5:
    print("Yin")
else:
    print("Yang")
Yang