10
1 The First Few Steps
1.2.4 Mathematical Notation Versus Coding
Make sure you understand that, from the outset, we had a pure mathematical
formulation of our formula
y = v 0 t − 0.5gt
2 ,
which does not contain any connection to programming at all. Remember, this
formula was derived hundreds of years ago, long before computers entered the
scene! When we next wrote a piece of code that applied this formula, that code had
to obey the rules of the programming language, which in this case is Python. This
means, for example, that multiplication had to be written with a star, simply because
that is the way multiplication is coded in Python. In some other programming
language, the multiplication could in principle have been coded otherwise, but the
mathematical formulation would still read the same.
We have seen how the equals sign (=) is interpreted in Python code. This
interpretation is very different from the interpretation in mathematics, as might be
illustrated by the following little example. In mathematics, x = 2 − x would imply
that 2x = 2, giving x = 1. In Python code, however, a code line like x = 2 -
x would be interpreted, not as an equation, but rather as an assignment statement:
compute the right hand side by subtracting the current value of x from 2 and let the
result be the new value of x. In the code, the new value of x could thus be anything,
all depending on the value x had above the assignment statement!
1.2.5 Write and Run Your First Program
Reading only does not teach you computer programming: you have to program
yourself and practice heavily before you master mathematical problem solving via
programming. In fact, this is very much like learning to swim. Nobody can do that
by just reading about it! You simply have to practice real swimming to get good
at it. Therefore, it is crucial at this stage that you start writing and running Python
programs. We just went through the program ball.py above, so let us next write
and run that code.
But first a warning: there are many things that must come together in the right
way for ball.py to run correctly. There might be problems with your Python
installation, with your writing of the program (it is very easy to introduce errors!),
or with the location of the file, just to mention some of the most common difficulties
for beginners. Fortunately, such problems are solvable, and if you do not understand
how to fix the problem, ask somebody. Very often the guy next to you experienced
the same problem and has already fixed it!
Start up Spyder and, in the editor (left pane), type in each line of the program
ball.py shown earlier. Then you save the program (select File -> save as) where
you prefer and finally run it (select Run -> Run, . . . or press F5). With a bit of luck,
you should now get the number 1.2342 out in the rightmost lower pane in the Spyder
GUI. If so, congratulations, you have just executed your first self-written computer
program in Python!
Précédent

- 32/350

Suivant