An offshore weather station runs a Python script to calculate the average of wind speed readings captured over a 1-hour window:
def process_wind_data(readings):
total_speed = 0
for speed in readings:
total_speed += speed
average_speed = total_speed / len(readings)
return average_speed
During a severe storm, the telemetry link is temporarily lost, causing the readings list to be passed to the function as an empty list, []. This causes the program to crash, terminating the logging process.
Which of the following correctly classifies the type of error that occurred, and identifies the best defensive programming technique to make this code robust?
It is a syntax error because dividing by zero is mathematically undefined, preventing the interpreter from compiling the line. It can be fixed by using a try-except block to catch a SyntaxError.
It is a runtime error (specifically a division-by-zero exception) because the code is syntactically correct but fails during execution when readings is empty. It can be prevented using validation to check if len(readings) > 0 before division.
It is a logic error because the formula for the average is incorrect for an empty dataset. It can be prevented by initializing total_speed = None and ensuring the program always runs to completion.
It is a syntax error because the interpreter cannot determine the type of elements inside readings at runtime. It can be resolved by using static type hinting, such as readings: list[float], to guarantee the list is never empty.
27 exam-style questions on AQA GCSE Computer Science Robust and secure programming. Each one has a worked solution and a mark scheme showing where the marks go.