Write a program to read in the data from the file swallow-speeds.txt
and use it to calculate the average air-speed velocity of an (unladen) African swallow. Use exceptions to handle the processing of lines which do not contain valid data points.
In the program below, we read in the lines of the supplied file as strings, but pass over those which raise a ValueError
when converted to float
.
# ex4-1-b-swallow-speeds-a.py
f = open('swallow-speeds.txt', 'r')
speeds = []
for line in f.readlines():
try:
speeds.append(float(line))
except (ValueError):
pass
f.close()
average_speed = sum(speeds)/len(speeds)
print('The average speed of an unladen African swallow is {:.1f} m/s'
.format(average_speed))
Output:
The average speed of an unladen African swallow is 10.3 m/s