──────────────────────────────────────

41. Reliable Automation · Reject One Bad Row and Keep Going

Validate a field safely and continue to the next record.

Lesson files · lessons/reliable-automation/validate-a-record

Before you start
- Convert text with int() and catch ValueError.
- Update a running total inside a loop.

By the end
- Total the valid non-negative quantities and count the invalid lines.
- Use a test with zero to explain how a valid zero affects the report.

Where you can use it
Summarise a delivery sheet while showing the warehouse team how many quantities they need to correct.

A report should tell you about invalid input instead of stopping over the first bad row or quietly turning bad text into zero. Parse one record at a time. Catch the conversion error close to int() and keep a separate count of invalid rows.

Predict
Does the valid zero count as an invalid row?
- No.
- Yes.

Worked example (example.py)

total = 0
bad = 0
for raw in ["4", "oops", "0"]:
    try:
        total += int(raw)
    except ValueError:
        bad += 1
print(total)
print(bad)


Example result
4
1

Read three quantity lines. Sum valid non-negative integers and print Total: followed by the total, then Skipped: followed by the invalid count.

Starter program (starter.py)

total = 0
bad = 0
for raw in ["4", "oops", "0"]:
    try:
        total += int(raw)
    except ValueError:
        bad += 1
print(total)
print(bad)


Hint
Compare converted values to zero. A failed conversion and a negative number both count as invalid.

Case 1. Try the sample
Input
4
unknown
0
Expected output
Total: 4
Skipped: 1

Case 2. Negative quantity
Input
2
-1
6
Expected output
Total: 8
Skipped: 1

Stretch
Keep a list of skipped row numbers for a human to fix later.

Reflect
What might go wrong if a malformed row is counted as zero?

Check your prediction
No. It converts to an integer successfully.
