66
3 Loops and Branching
Fig. 3.1 Vertical position of ball
The loop will run as long as the condition y[i] >= 0 evaluates to True. Note
that the programmer introduced a variable by the name i, initialized it (i = 0)
before the loop, and updated it (i = i + 1) in the loop. So, each time the condition
y[i] >= 0 evaluates to True, i is explicitly increased by 1, allowing a check of
successive elements in the array y.
When the condition y[i] >= 0 evaluates to False, program execution proceeds
with the code lines after the loop. This means that, after skipping the comments, the
time of flight is printed, followed by a plotting of the heights (to allow an easy check
of the time of flight).
Reporting the Answer Remember that the height is computed at chosen points
in time only, so, most likely, we do not have the time for when the height is
exactly zero. Thus, reporting t[i] as the time of flight is an approximation. Another
alternative, could be to report 0.5*(t[i-1] + t[i]) as the answer, reasoning that
since y[i] is negative (which is why the loop terminated), t[i] must be too large.
Running the Program If you run this program, you get the printout
Time of flight (in seconds): 0.917918
and the plot seen in Fig. 3.1. The printed time of flight seems consistent with what
we can read off from the plot.
3.2.2 Characteristics of a Typical while Loop
Loop Structure and Interpretation The structure of a typical while loop may be
put up as
while some_condition:
# Loop header

# 1st line in loop body
Précédent

- 88/350

Suivant