Challenge: Clean the Data
Completed
A form collected people's ages, but some entries are rubbish. Read the entries, ignore anything that isn't a whole number, and also ignore numbers below 0 or above 120.
Input
A count n, then n lines of entries.
Output
Valid: <how many valid ages> Invalid: <how many were skipped> Average: <average of the valid ages, 1 decimal>
If no age is valid, print Average: none as the last line.
Example
Input
5 21 abc 35 -4 40
Output
Valid: 3 Invalid: 2 Average: 32.0
Editor
Python
Hints
Use try/except ValueError around int().
continue skips to the next entry.
Check the range with 0 <= age <= 120.
Solution explanation
Each entry is tried as a number. Bad text is caught by except; numbers outside the range are counted as invalid with a normal if.
Show solution
ages = []
bad = 0
for _ in range(int(input())):
entry = input()
try:
age = int(entry)
except ValueError:
bad += 1
continue
if 0 <= age <= 120:
ages.append(age)
else:
bad += 1
print("Valid:", len(ages))
print("Invalid:", bad)
if ages:
print(f"Average: {sum(ages) / len(ages):.1f}")
else:
print("Average: none")