3.2 The while Loop
65
An example of how to use break and continue can be found in Sect. 5.2
(times_tables_4.py).
The break and continue statements may also be used in while loops, to be
treated next.
3.2 The while Loop
The other basic loop construction in Python is the while loop, which runs as long as
a condition is True. Let us move directly to an example, and explain what happens
there, before we consider the loop more generally.
3.2.1 Example: Finding the Time of Flight
To demonstrate a while loop in action, we will make a minor modification of the
case handled with ball_plot.py in Sect. 1.5. Now, we choose to find the time of
flight for the ball.
The Case Assume the ball is thrown with a slightly lower initial velocity, say
4.5 ms −1 , while everything else is kept unchanged. Since we still look at the first
second of the flight, the heights at the end of the flight will then become negative.
However, this only means that the ball has fallen below its initial starting position,
i.e., the height where it left the hand, so there is nothing wrong with that. In an array
y, we will then have a series of heights which towards the end of y become negative.
As before, we will also have an array t with all the times for corresponding heights
in y.
The Program In a program named ball_time.py, we may find the time of flight
as the time when heights switch from positive to negative. The program could look
like this
import numpy as np
v0 = 4.5
# Initial velocity
g = 9.81
# Acceleration of gravity
t = np.linspace(0, 1, 1000) # 1000 points in time interval
y = v0*t - 0.5*g*t**2
# Generate all heights
# Find index where ball approximately has reached y=0
i = 0
while y[i] >= 0:
i = i + 1
# Since y[i] is the height at time t[i], we do know the
# time as well when we have the index i...
print(’Time of flight (in seconds): {:g}’.format(t[i]))
# We plot the path again just for comparison
import matplotlib.pyplot as plt
plt.plot(t, y)
plt.plot(t, 0*t, ’g--’)
plt.xlabel(’Time (s)’)
plt.ylabel(’Height (m)’)
plt.show()
Précédent

- 87/350

Suivant