Advanced · Exceptions · 189 of 264
Count the bad lines
Read lines until the line END. Add up the lines that are whole numbers; count the lines that are not.
Input: lines, the last one END. Output: Sum: <sum> on the first line, Invalid: <count> on the second.
Examples
Input
1 2 three 4 END
Output
Sum: 7 Invalid: 1
Input
END
Output
Sum: 0 Invalid: 0
Input
x y -5 END
Output
Sum: -5 Invalid: 2
One more test checks other inputs when you press Check.
Stuck? The idea behind exceptions
A try block runs code that might fail; its except catches the error and lets the program carry on, instead of stopping.
Catch the error you expect, by name: ValueError for int("abc"), ZeroDivisionError for dividing by 0.
for line in ["4", "x", "7"]:
try:
print(int(line) * 2)
except ValueError:
print("not a number")Watch for: A bare except: hides every mistake, your own typing errors too. Name the error.