
A data project should not hand over a notebook cluttered with intermediate output. What it owes the reader is an answer whose input, transformations, and limits can all be examined by someone else. The question here is a narrow one: what do the known order totals look like by region in a small supplied export?
Choose a project by its question
Choose the result you need, then try the supplied synthetic fixture before substituting your own export. The library offers three runnable projects, each built around a distinct question and set of checks:
Scroll sideways if the columns extend beyond the frame.
| Project | Question and saved or printed result | Starting skills |
|---|---|---|
| CSV validation report, built below | What are the accepted order totals by region? Writes report.md with rejected rows and a source fingerprint. |
Read a CSV; standard-library Python |
| Regional order summary | How many orders have known amounts? Prints row counts, nonmissing counts, and totals, keeping a missing-region group. | A virtual environment and pandas 2.2.3 |
| Customer-match audit | Which orders lack a matching customer? Prints unmatched orders and checks that the join has not multiplied rows. | DataFrame columns and a many-to-one lookup |
Everything in the walkthrough below relies on the standard library alone, so the first project stays small enough for you to verify each exclusion and total by hand. The two linked projects carry the same analysis habits into grouping and joins. Treat them as alternatives to start with, not as added dependencies for this report.
Updated November 26, 2026: the comparison above now helps you choose a task. The six-order fixture, its calculations, and the downloadable script remain unchanged.
Name the question and the exclusions
The code needs only standard-library Python 3.11+, with no external packages. The fixture holds six synthetic orders, and a valid record must carry a non-empty region name plus a nonnegative integer cent amount. Rows with a missing region, a bad numeral, or a negative value are rejected and logged.
These totals include only accepted rows; they are not a complete measure of business revenue. State that limitation in the output, because rejected records may change the actual total.
Save the code as analysis.py in an empty project directory and run python analysis.py.
import csv
import hashlib
import re
from collections import defaultdict
from io import StringIO
from pathlib import Path
DATA = """id,region,cents
1,north,1200
2,north,800
3,south,1000
4,south,500
5,,900
6,north,broken
"""
totals = defaultdict(int)
rejected = []
accepted = 0
for row_number, row in enumerate(csv.DictReader(StringIO(DATA)), 2):
if not row["region"] or not re.fullmatch(r"[0-9]+", row["cents"]):
rejected.append(row_number)
continue
totals[row["region"]] += int(row["cents"])
accepted += 1
assert accepted + len(rejected) == 6
assert dict(totals) == {"north": 2000, "south": 1500}
lines = ["# Known order totals", "", "Synthetic exercise data.", "",
f"Accepted: {accepted}; rejected: {len(rejected)}.",
f"Rejected source rows: {rejected}.", "",
"These totals exclude rejected rows and are incomplete if those rows contain sales.", ""]
lines += [f"- {region}: {cents} cents" for region, cents in sorted(totals.items())]
lines += ["", "Source SHA-256: " + hashlib.sha256(DATA.encode()).hexdigest()]
report = Path("report.md")
with report.open("x", encoding="utf-8") as target:
target.write("\n".join(lines) + "\n")
print(report.resolve())
Inspect the deliverable
Once the script finishes, it writes report.md to your working directory and prints the full file path in the terminal. The file lists four accepted records, two rejected records, 2000 cents for north, and 1500 cents for south, plus a source digest that links the output to this exact version of the input.
The script deliberately refuses to replace an existing report, so a rerun cannot erase a result you planned to compare without warning. Review the current report first, then rename it or remove that generated file alone before running the analysis again.
Scroll sideways if the columns extend beyond the frame.
| Project design choice | Why analysis.py uses it |
What happens if you omit it |
|---|---|---|
Integer cents (int(row["cents"])) |
Exact addition across accepted regional orders | Binary floating-point rounding drift in currency totals |
Explicit row-conservation check (accepted + len(rejected) == 6) |
Proves no input row was silently skipped by a branch | Filter mistakes can drop records without changing exit status |
Sorted output (sorted(totals.items())) |
Produces byte-identical Markdown lines across runs | Dictionary insertion order depends on first-seen row order |
Exclusive file creation (report.open("x", encoding="utf-8")) |
Raises FileExistsError instead of clobbering prior output |
Previous run artifacts get overwritten before comparison |
Embedded input checksum (hashlib.sha256(DATA.encode()).hexdigest()) |
Ties the generated Markdown report to the exact input bytes | Readers cannot tell which version of the CSV produced the numbers |
Make the pipeline reviewable and separate raw input from output
Raw source data should never be edited in place. This standalone script embeds an inline string for convenience, but a full project keeps untouched source exports under data/raw/ and sends everything it generates to reports/ or build/. Record the export’s source, the license or permission that allows its use, and its extraction date. A SHA-256 digest can confirm that two runs used identical bytes; by itself, however, a cryptographic hash says nothing about whether the upstream export was complete or representative.
Rejections deserve a place beside the totals in the final analysis. The header occupies row 1 of this six-order sample, so order IDs 5 and 6 appear on source row 6 (5,,900), missing its region, and source row 7 (6,north,broken), holding a non-numeric price; the result is Rejected source rows: [6, 7]. If readers assume every order succeeded, reporting north at 2000 cents without flagging the rejected north order gives them a false picture. For confidential data, put row numbers and structured rejection codes in the shared Markdown report, not raw personal details.
The checks protect two invariants when you run locally: no input record vanishes silently, and the regional sums match the known fixture. Python’s -O flag strips every assert statement, so production CLI tools and batch jobs should replace assert with explicit if ...: raise ValueError(...) guards that work whatever flags the runtime receives.
Turn the exercise into your own project
Add a seventh valid order first, and work out the expected total before running the script. Update both assertions to reflect the added row and revised regional totals; otherwise, the fixture’s original checks will correctly stop the run before it writes a report. Then add a record with an invalid amount and raise the expected row count. The accepted sum stays put while the rejection tally goes up. Finally, insert a brand-new region to confirm that report sorting stays deterministic, and rename any existing report.md first so the exclusive-write guard lets the new run finish.
Document the command, Python version, expected files, and rejection policy in a short README. Use the README guide for a starting structure. Before replacing the synthetic fixture with a larger export, test the parser with pytest.
Once your analysis extends to repeat buyers or customer demographics, add a dedicated customer table and validate the join relationship before you aggregate. Save dashboards for later, after the underlying table is solid. For a first project, an honest text report that documents its exclusions is worth more than a polished chart drawn from messy records.
Source: Python hashlib documents the checksum operation; csv documents record parsing.
Download the complete example. Save the file before running it; the guide above names the required runtime.
Keep building
- SQL window functions: running totals without losing rows
Use a stable row order and an explicit frame to calculate a running total and rank within each account.
- SQL GROUP BY: make the unit of analysis explicit
Build a category report with COUNT, SUM, HAVING, and deterministic ordering on a supplied dataset.
- SQL joins: keep the customers who have no orders
Compare inner and left joins on a tiny reproducible database, including the filter that changes your result.