(Credit Chapter 2, Newman).
Usually many ways to write a programme to do what you need to do.
e.g.
Well written code:
Poorly written code:
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).
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")
e.g. Use $E$ for energy and $t$ for time.
Use full words if necessary
Integer type for integers (etc).
Start your code with a set of import statements.
e.g.
import numpy as np
import scipy as sci
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).
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).
Particularly important for code that runs for a long time.
for n in range(1000000):
if n%1000==0:
print("Step",n)
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
(A general rule for life as well as coding!).
Write your code in as few lines as possible.
In [ ]: