Average of readings from a file with a blank line

A rain gauge logger saves daily rainfall in millimetres to a file named rain.txt, one reading per line. A power glitch left the third line empty. Every line, including the empty one, ends with a newline character. The file contents are:


Plain text
12.5
8.0

7.25
3.0
4.6


The following Python program processes the file:


Python
total = 0.0
count = 0
with open("rain.txt") as f:
    for line in f:
        if line.strip() == "":
            continue
        total += float(line)
        count += 1
print(round(total / count, 2))


What value does the program print? Give the value in millimetres, to two decimal places.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More File Input/Output Questions: