Divide 100 by each value on a list, keeping track of what went wrong.
What to build
A loop that survives bad lines and reports them at the end.
Requirements
- For each line, print the whole-number result of
100 // value. - Print
bad numberif the line is not a whole number. - Print
zeroif the value is 0. - At the end, print
ok A, bad B, zero C.
Input
The first line has n. Each of the next n lines is some text.
Output
One line per input line, then the summary.
Constraints
n is from 1 to 100.
Example
Input:
3
5
x
0
Output:
20
bad number
zero
ok 1, bad 1, zero 1
Why it works
Placing try inside the loop limits each failure to one line. Keeping one small try around the risky lines shows exactly what could go wrong.
Examples
Example 1 · Input
3 5 x 0
Expected output
20 bad number zero ok 1, bad 1, zero 1
Example 2 · Input
1 3
Expected output
33 ok 1, bad 0, zero 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Use two except blocks, one for each kind of error.
Hint 2
Count the failures in separate variables.
Hint 3
try belongs inside the loop, so that one bad line does not end the program.
Solution
Show one correct solution (try it yourself first)
n = int(input())
ok = bad = zero = 0
for _ in range(n):
try:
value = int(input())
print(100 // value)
ok += 1
except ValueError:
print("bad number")
bad += 1
except ZeroDivisionError:
print("zero")
zero += 1
print(f"ok {ok}, bad {bad}, zero {zero}")