12
1 The First Few Steps
What about units?
The observant reader has noticed that the handling of quantities in ball.py
did not include units, even though velocity (v0), acceleration (g) and time (t)
of course do have the units of ms −1 , ms −2 , and s, respectively. Even though
there are tools a in Python to include units, it is usually considered out of scope
in a beginner’s book on programming. So also in this book.
a See, e.g., https://github.com/juhasch/PhysicalQuantities, https://github.com/hgrecco/pint
and https://github.com/hplgit/parampool if you are curious.
1.3 A Python Program with a Library Function
Imagine you stand on a distance, say 10.0 m away, watching someone throwing a
ball upwards. A straight line from you to the ball will then make an angle with the
horizontal that increases and decreases as the ball goes up and down. Let us consider
the ball at a particular moment in time, at which it has a height of 10.0 m. What is
the angle of the line then?
Well, we do know (with, or without, a calculator) that the answer is 45 ◦ . However,
when learning to code, it is generally a good idea to deal with simple problems
with known answers. Simplicity ensures that the problem is well understood before
writing any code. Also, knowing the answer allows an easy check on what your
coding has produced when the program is run.
Before thinking of writing a program, one should always formulate the algorithm, i.e., the recipe for what kind of calculations that must be performed. Here,
if the ball is x m away and y m up in the air, it makes an angle θ with the ground,
where tan θ = y/x. The angle is then tan −1 (y/x).
The Program Let us make a Python program for doing these calculations. We
introduce names x and y for the position data x and y, and the descriptive name
angle for the angle θ . The program is stored in a file ball_angle_first_try.py:
x = 10.0
# Horizontal position
y = 10.0
# Vertical position
angle = atan(y/x)
print((angle/pi)*180)
Before we turn our attention to the running of this program, let us take a look
at one new thing in the code. The line angle = atan(y/x), illustrates how the
function atan, corresponding to tan −1 in mathematics, is called with the ratio y/x
as argument. The atan function takes one argument, and the computed value is
returned from atan. This means that where we see atan(y/x), a computation
is performed (tan −1 (y/x)) and the result “replaces” the text atan(y/x). This is
actually no more magic than if we had written just y/x: then the computation of
Précédent

- 34/350

Suivant