A text file scores.txt stores one integer test score on each line, for example:
60
75
90Write a Python function average_score(filename) that:
- returns the mean of all the scores in the file;
- returns 0 if the file contains no scores;
- returns
Noneif the file does not exist.
[6]
- Opens the file for reading (using
open, preferably withwithso it is closed)(1) - Reads the file line by line (or all lines) with a loop (allow a list comprehension over the file or over
f.read().split())(1) - Converts each line to an integer using
int()(allow with or without.strip(), sinceint()ignores surrounding whitespace and the newline)(1) - Accumulates the total and the number of scores (allow building a list of the scores and using
sum()andlen())(1) - Avoids division by zero: returns 0 when there are no scores, otherwise returns total ÷ count(1)
- Uses try/except FileNotFoundError (or equivalent check) to return None for a missing file(1)
- Answer:
def average_score(filename): try: with open(filename, "r") as f: total = 0 count = 0 for line in f: line = line.strip() if line != "": total += int(line) count += 1 except FileNotFoundError: return None if count == 0: return 0 return total / count - Examiner tip: Check for an empty file before dividing, otherwise total / count raises ZeroDivisionError; int() copes with the trailing newline on its own.