A developer writes a function to calculate the average of a list of numbers, but the function sometimes returns a wrong result when the list contains non-numeric values. What is the best way to handle this?
Trap 1: Return None if any non-numeric value is encountered.
Returning None may cause silent errors downstream.
Trap 2: Use try-except to ignore non-numeric values and proceed with the…
Ignoring values may produce inaccurate results.
Trap 3: Convert all values to string and concatenate them.
Concatenating strings does not give an average.
- A
Return None if any non-numeric value is encountered.
Why wrong: Returning None may cause silent errors downstream.
- B
Use try-except to ignore non-numeric values and proceed with the remaining numbers.
Why wrong: Ignoring values may produce inaccurate results.
- C
Convert all values to string and concatenate them.
Why wrong: Concatenating strings does not give an average.
- D
Check that all items are numeric before calculation, and raise TypeError otherwise.
Raising an exception is the standard way to handle invalid input.