Good Coding Style

(Credit Chapter 2, Newman).

Usually many ways to write a programme to do what you need to do.

e.g.

  • you choose the variable names
  • lists or arrays?
  • how to break code into user defined functions?

Well written code:

  • a simple structure
  • easy to read and understand
  • ideally, run fast

Poorly written code:

  • convoluted or unnecessarily long
  • difficult to follow
  • may run slowly

Making code easy to understand is incredibly important (not just to make marking it easier, but for your own future use, and if anyone else needs to edit your code in future).

Top Tips for Good Coding Style

1. Include comments in your programs.

You may think this is less important with Notebooks, but if you wish to copy just the code box, having comments to remind yourself of what the variable mean, or what is happening where is very useful.

#This is a comment
print("This would write a comment out which is also useful")

2. Use meaningful variable names.

e.g. Use $E$ for energy and $t$ for time.

Use full words if necessary

3. Use the right types of variables.

Integer type for integers (etc).

4. Import functions first.

Start your code with a set of import statements.

e.g.

import numpy as np
import scipy as sci

5. Give your constants names.

For standard constants make use of the scipy.constants module.

For custom values have a section at the start of the code to define them (makes it easier to change later).

6. Employ user-defined functions, where appropriate.

Make your code shorter by writing a function for any extended operation which will repeat many times.

However - avoid overuse: simple operations that can be represented by just a line or two of code are better kept in the main body.

Normally put all functions at the top of the code (not mixed in with the main body of the code).

7. Print out partial results and updates throughout your program.

Particularly important for code that runs for a long time.

for n in range(1000000):
    if n%1000==0:
    print("Step",n)

8. Lay out your programs clearly.

Split your code into logical blocks.

Make use of white space (has no meaning in python).

Split long lines

energy = mass*(vx**2 + vy**2)/2 + mass*g*y \
                 + moment_of_inertia*omega**2/2

9. Don’t make your programs unnecessarily complicated.

(A general rule for life as well as coding!).

Write your code in as few lines as possible.


In [ ]: