Worked tutorial · about 35 minutes
Audit a CSV before asking AI to summarize it
Check an eight-record workshop file for duplicates, missing fields and invalid numbers. Produce a reproducible audit before writing a summary.
Original editorial exercise · fictional practice data · checked 23 October 2026
A fluent summary can hide a broken spreadsheet. In this tutorial, your deliverable is a small audit: which records are usable, why the others were rejected, and which totals the usable records support. You do not need an AI account, a paid tool, or any Python packages.
1. Save the fictional input and define the rules
Download both files into a fresh folder. Use Python 3 in a terminal. The workshop names, bookings and amounts are invented; they do not describe a real business. Keep the input unchanged so that someone else can reproduce your answer.
booking_id,topic,seats,unit_price
B001,"AI, first steps",2,15.00
B002,Prompt clinic,1,20.00
B001,"AI, first steps",2,15.00
B003,,1,15.00
B004,Data lab,-1,30.00
B005,Model lab,3,n/a
B006,Data lab,2,0.00
B007,Prompt clinic,0,20.00
For this exercise, each booking ID may appear once; its first occurrence reserves the ID. A topic must be present. Seats must be a positive whole number. The unit price must be a finite, nonnegative amount with at most two decimal places. A price of zero is valid because a workshop may be free. Reject later duplicate IDs rather than guessing which copy was intended.
These are exercise rules, not universal cleaning rules. In a real file, establish the business meaning of duplicates and zero values with its owner before deleting or changing anything.
2. Inspect the records before calculating
- Read the header and check the four fields. Treat the quoted comma in
"AI, first steps"as part of the topic, not an extra column. - Write down the IDs you would accept. For every rejected data record, record one clear reason. Count data records starting at 1, without counting the header.
- Add seats only from accepted records. For each accepted booking, multiply seats by unit price, then add those amounts. Do not replace
n/awith zero.
Try this by hand first. A parser is useful for repeating your rules, but it cannot decide whether those rules match the source. Splitting each line with split(',') will mishandle this file's quoted topic; use a CSV reader.
3. Run the read-only audit
python audit_bookings.py bookings.csv The script reads the file and prints JSON. It does not edit the CSV or send it to a service. It uses Python's CSV parser for quoting, explicit integer conversion for seats, and decimal arithmetic for the illustrative amounts. Inspect the solution after making your own attempt.
Show the complete Python solution
"""Audit fictional workshop bookings. Python 3, standard library only.
Usage: python audit_bookings.py bookings.csv
Reads the original file; prints JSON; does not rewrite records or call a service.
"""
import csv
import json
import sys
from decimal import Decimal, InvalidOperation
def audit(filename):
accepted, issues, seen = [], [], set()
with open(filename, encoding="utf-8-sig", newline="") as stream:
reader = csv.DictReader(stream)
if reader.fieldnames != ["booking_id", "topic", "seats", "unit_price"]:
raise ValueError("Expected header: booking_id,topic,seats,unit_price")
for number, row in enumerate(reader, start=1):
reason = None
booking_id = (row.get("booking_id") or "").strip()
topic = (row.get("topic") or "").strip()
if None in row or any(value is None for value in row.values()):
reason = "wrong column count"
elif not booking_id:
reason = "missing booking_id"
elif booking_id in seen:
reason = "duplicate booking_id"
# The first occurrence reserves an ID, even if another field is invalid.
if booking_id:
seen.add(booking_id)
if reason is None and not topic:
reason = "missing topic"
if reason is None:
try:
seats = int(row["seats"])
if str(seats) != row["seats"].strip() or seats <= 0:
raise ValueError
except ValueError:
reason = "seats must be a positive whole number"
if reason is None:
try:
price = Decimal(row["unit_price"])
if not price.is_finite() or price < 0 or price.as_tuple().exponent < -2:
raise InvalidOperation
except InvalidOperation:
reason = "unit_price must be a nonnegative amount with at most two decimals"
if reason:
issues.append({"record": number, "booking_id": booking_id, "reason": reason})
else:
accepted.append({"booking_id": booking_id, "topic": topic, "seats": seats, "price": price})
total = sum((row["seats"] * row["price"] for row in accepted), Decimal("0"))
return {"accepted_ids": [row["booking_id"] for row in accepted],
"accepted_records": len(accepted), "rejected_records": len(issues),
"seats": sum(row["seats"] for row in accepted),
"booking_value": format(total, ".2f"), "issues": issues}
if __name__ == "__main__":
if len(sys.argv) != 2:
raise SystemExit("Usage: python audit_bookings.py bookings.csv")
print(json.dumps(audit(sys.argv[1]), indent=2))
4. Compare with the answer key
Show accepted records, rejected records and totals
Accept B001, B002 and B006: 3 records, 5 seats, and a fictional booking value of 50.00. The calculation is 2 × 15.00 + 1 × 20.00 + 2 × 0.00.
- Record 3, B001: duplicate ID.
- Record 4, B003: missing topic.
- Record 5, B004: negative seat count.
- Record 6, B005: invalid unit price.
- Record 8, B007: zero seats, which this exercise excludes.
The free B006 booking remains in the seat count. There are five rejected records; rejecting a record is different from proving that its real-world booking should be cancelled.
5. Write a summary with its limits
A supported summary is: “Under the stated audit rules, three usable records represent five seats and a booking value of 50.00; five records need correction or duplicate review.” It would be unsupported to call this collected revenue, attendance, profit, or demand. The file contains no payments, costs, cancellations or actual participation.
If you use an approved AI tool to help write the summary, give it the audit output and rules. Require it to keep rejected records separate and to leave absent facts unknown. Compare its sentences with the output yourself. Use the supplied fictional data rather than uploading customer or workplace information just to try the exercise.
Choose your next lesson from the error
If reading the CSV or handling exceptions was difficult, work on Python fundamentals. If the code ran but your summary counted rejected records or invented payment status, practice data definitions and evidence checks. For a different task, try the existing source-based office checklist; for model evaluation, continue to the classifier threshold tutorial.
Sources and scope
The dataset, rules, code and answer key are our editorial exercise, not an official course assignment. Python's CSV documentation explains the parser, and its decimal documentation explains decimal arithmetic. Checked 23 October 2026.