Worked example 1
A text file named results.txt contains student scores, one per line. Some lines may be empty or contain non-numeric text. Write a Python program to read the scores, calculate the average of the valid scores, and print the result. The program must handle the case where results.txt does not exist and ignore invalid lines.
results.txt content:
85
92
78
---
65
Show solution outline
def calculate_average_score():
total_score = 0
valid_scores_count = 0
try:
with open('results.txt', 'r') as file:
for line in file:
# .strip() removes whitespace and newline characters
cleaned_line = line.strip()
if cleaned_line: # Check if line is not empty
try:
score = int(cleaned_line)
total_score += score
valid_scores_count += 1
except ValueError:
# This line is not a valid integer, so we ignore it.
print(f"Ignoring invalid line: '{cleaned_line}'")
if valid_scores_count > 0:
average = total_score / valid_scores_count
print(f"Average score: {average:.2f}")
else:
print("No valid scores found.")
except FileNotFoundError:
print("Error: results.txt not found.")
# --- Execution ---
calculate_average_score()
# --- Expected Output ---
# Ignoring invalid line: '-- -'
# Average score: 80.00
Mark Scheme:
- [1] try...except FileNotFoundError block used correctly.
- [1] File opened for reading ('r') using with open().
- [1] Iterates through lines of the file.
- [1] Inner try...except ValueError to handle non-numeric data.
- [1] Correctly calculates and accumulates total and count for valid scores.
- [1] Correctly calculates and prints the average, handling division by zero.