1.8 Concluding Remarks
35
messages. This also goes for lower and upper case letters. If you (after importing
from math) give the command pi, you get 3.1415 . . .. However, if you write Pi,
you get an error message. Pay attention to such details also when they are given in
later chapters.
1.8.2 Write Readable Code
When you write a computer program, you have two very different kinds of
readers. One is Python, which will interpret and run your program according to
the rules. The other is some human, for example, yourself or a peer. It is very
important to organize and comment the code so that you can go back to your
own code after, e.g., a year and still understand what clever constructions you
put in there. This is relevant when you need to change or extend your code
(which usually happens often in reality). Organized coding and good commenting
is even more critical if other people are supposed to understand code that you have
written.
It might be instructive to see an example of code that is not very readable. If we
use our very first problem, i.e. computing the height y of a ball thrown up in the air,
the mathematical formulation reads:
y = v 0 t − 0.5gt
2 .
Now, instead of our previous program ball.py, we could write a working program
(in bad style!) like:
# This is an example of bad style!
m=5;u=9.81;y=0.6
t=m*y-u*0.5*y**2;print(t)
Running this code, would give the correct answer printed out. However, upon
comparison with the mathematical writing, it is not even clear that the two are
related, unless you sit down and look carefully at it!
In this code,
• variable names do not correspond to the mathematical variables
• there are no (explaining) comments
• no blank lines
• no space to each side of = and -
• several statements appear on the same line with no space in between
When comparing this “bad style” code to the original code in ball.py, the point
should be clear.
1.8.3 Fast Code or Slower and Readable Code?
In numerical computing, there is a strong tradition for paying much attention to fast
code. Industrial applications of numerical computing often involve simulations that
Précédent

- 57/350

Suivant