Safe reading average
A sensor export contains space-separated tokens; damaged readings appear as non-numeric text. Ignore tokens that cannot be converted to numbers. Print the average of valid readings to two decimals, or NO DATA if none are valid.
Input
One line containing 1 to 100 space-separated tokens.
Output
The valid-reading average with two decimal places, or NO DATA.
Example 1
Input
10 bad 20 15x 30
Output
20.00
Only 10, 20 and 30 are valid, so their average is 20.
Constraints
- Valid readings are between -10000 and 10000
- Invalid tokens contain no whitespace
Hints
Hint 1 of 3
float(token) raises ValueError for damaged text.
Hint 2 of 3
Catch only ValueError and keep scanning.
Hint 3 of 3
Check whether the values list is non-empty before dividing.
Solution
Show a reference solution and explanation
values = []
for token in input().split():
try:
values.append(float(token))
except ValueError:
pass
if values:
print(f"{sum(values) / len(values):.2f}")
else:
print("NO DATA")
Why it works
The narrow exception handler skips only conversion failures instead of hiding unrelated bugs. The explicit empty-list branch also prevents division by zero and states clearly when no usable data exists.
Lesson for this exercise: Exceptions and Error Handling in Python