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

70. Make Your Own Python Tool · Test on Data You Didn’t Write

Differentiate a malformed row from a repeated valid row and test recovery.

Lesson files · lessons/make-your-own-tool/test-unfamiliar-data

Before you start
- Read CSV fields by name and reject malformed quantities.
- Use a set to remember accepted IDs.

By the end
- Test an unfamiliar CSV and account for every row as accepted, invalid or duplicate.
- Use a corrected row to explain why an invalid row must leave its ID available.

Where you can use it
Check a partner’s export before trusting totals from it, and use a corrected row to diagnose IDs your program reserved too early.

An export can include a repeated ID, an empty ID or text where a quantity should be. First decide if a row is valid. Then check whether you have already accepted its ID.

Take a CSV from another person and label each row on paper as accepted, invalid or duplicate. Add up the three counts and compare them with the program. If they differ, find the first row where your prediction and code disagree. Pay special attention to invalid rows followed by corrections using the same ID.

Predict
An invalid row has ID L7. A corrected row with ID L7 comes next. What should happen?
- Reject the corrected row as a duplicate.
- Accept the corrected row.

Worked example (example.py)

seen = set()
for item_id in ["L1", "L1", "L2"]:
    if item_id in seen:
        print("Repeat")
        continue
    seen.add(item_id)
    print("Accept")


Example result
Accept
Repeat
Accept

Read id,quantity CSV from Program input. Print Accepted, Invalid and Duplicates counts on separate lines. An empty ID, a missing quantity or a negative or non-integer quantity is invalid. Ignore spaces around the ID. After accepting an ID, count a later valid row with that ID as a duplicate.

When the supplied cases pass, ask a partner for a new CSV with these headers. Compare the counts you predicted with the three lines the program prints.

Starter program (starter.py)

import csv
import sys

rows = csv.DictReader(sys.stdin)
for row in rows:
    print(row["id"])


Starter input
id,quantity
A1,2
A1,5
A2,wrong
A2,0

Hint
Place validation and both continue statements before seen.add(). Report len(seen) as the accepted count.

Case 1. Try the sample
Input
id,quantity
A1,2
A1,5
A2,wrong
A2,0
Expected output
Accepted: 2
Invalid: 1
Duplicates: 1

Case 2. Blank IDs and negative counts
Input
id,quantity
,5
B1,-1
B1,0
 B1 ,2
Expected output
Accepted: 1
Invalid: 2
Duplicates: 1

Case 3. A quiet week
Input
id,quantity
Expected output
Accepted: 0
Invalid: 0
Duplicates: 0

Stretch
Check that the three reported counts add up to the number of data rows. What other check would help you catch an accepted row that should have been rejected?

Reflect
Which row in the first test proves a broken entry did not block a valid correction?

Check your prediction
Accept the corrected row. Only an accepted row reserves its identifier.
