Household Numbers: the Mathematics CapstoneHousehold Numbers
0 / 0

Workbench / Household Numbers: the Mathematics Capstone

S1 · B1·01

The Household Ledger

Stage 1 of the household numbers capstone, after chapter 1: a month's spending recorded so that quantities, positions in time and labels are kept apart, totalled by hand and by a short program in whole paise, with the totals checked against each other.

6 topics · ~5 min read
Updated Suggest a correction

Stage 1: the household ledger

The brief

What you'll build. A ledger of one month of your household's spending: one line per payment, with its date, the account it came from, a category, a description and the amount. You'll total it by category by hand, then write a short program that reads the same ledger and produces the same totals, and you'll check that the two agree to the paisa.

Why a real household needs this. Every later stage (a budget, unit prices, a loan's EMI, inflation) starts from "where does the money actually go?", and most people's answer is a guess. A ledger turns the guess into numbers you can add, compare and question. It's also the first place chapter 1's distinctions matter: an account number is a label, a date is a position, and only the amounts are quantities.

Why now. Chapter 1 gives you exactly what this stage needs: which numbers you can add (cardinal), which only order things (ordinal), which are labels (nominal), and that a computer's numbers are a model with edges.

What you'll have at the end. A ledger file (ledger.csv), your hand totals, a program (ledger.py) whose totals match them, and a short note on any line where they didn't match at first and why.

Theory to own

Answer these in your own words before you build. Each points to where the book explains it.

  1. Three jobs. In a line like 2026-10-05, 30091877610, electricity, Bill for September, 1254.00, which values are quantities, which are positions and which are labels? Which can you add? (Chapter: "Three different jobs for numbers".)
  2. Why not a float for money? What does 0.1 + 0.2 give in Python, and why would a ledger of thousands of rupees-and-paise amounts drift if stored as floats? (Chapter: lab, experiment 4.)
  3. What "total" means. If the categories don't overlap and every line has exactly one, why must the category totals add up to the grand total? Which rule of arithmetic is that? (Chapter: "Rules that come from the stories".)
  4. Division with a remainder. Your school fees are paid in 3 instalments. If the annual fee doesn't divide by 3 exactly, what do you do with the remainder? (Chapter: "Division: sharing or grouping"; exercises, C1.)

Build it

Step 1: record a month. Use your own bank statement or wallet history, or the sample below if you'd rather not. One line per payment. Keep the date as YYYY-MM-DD (it sorts correctly as text), the account as text exactly as printed (leading zeros included), and the amount in rupees with two decimal places.

Text
date,account,category,description,amount
2026-10-01,00451200917,rent,October rent,22000.00
2026-10-03,00451200917,groceries,Weekly vegetables and milk,1840.50
2026-10-05,30091877610,electricity,Bill for September,1254.00
2026-10-10,00451200917,groceries,Rice 10 kg and dal,1612.00
2026-10-12,00451200917,transport,Metro card top-up,500.00
2026-10-17,00451200917,groceries,Weekly vegetables and milk,1795.25
2026-10-20,30091877610,school,Term fees (instalment 2 of 3),15000.00
2026-10-28,00451200917,groceries,Weekly vegetables and milk,1903.75

Step 2: total it by hand. Add each category's amounts on paper, then add the category totals, then add every line directly as a check. Use the strategies from chapter 1 and chapter 3: group amounts that make round numbers (1795.25+1903.75=3699.00).

Step 3: write the program. Read the CSV, convert each amount to whole paise (an integer), keep account and date as text, and total by category. Here is a version to compare yours with:

Python
"""Household numbers, stage 1: a ledger that keeps quantities, positions and labels apart."""
import csv, io

SAMPLE = """date,account,category,description,amount
2026-10-01,00451200917,rent,October rent,22000.00
2026-10-03,00451200917,groceries,Weekly vegetables and milk,1840.50
2026-10-05,30091877610,electricity,Bill for September,1254.00
2026-10-10,00451200917,groceries,Rice 10 kg and dal,1612.00
2026-10-12,00451200917,transport,Metro card top-up,500.00
2026-10-17,00451200917,groceries,Weekly vegetables and milk,1795.25
2026-10-20,30091877610,school,Term fees (instalment 2 of 3),15000.00
2026-10-28,00451200917,groceries,Weekly vegetables and milk,1903.75
"""

def paise(text):
    """'1840.50' -> 184050. Money is counted in whole paise, never as a float."""
    rupees, _, frac = text.partition(".")
    frac = (frac + "00")[:2]
    if not (rupees.isdigit() and frac.isdigit()):
        raise ValueError(f"not an amount: {text!r}")
    return int(rupees) * 100 + int(frac)

def load(text):
    rows = []
    for r in csv.DictReader(io.StringIO(text)):
        rows.append({"date": r["date"],                # ordinal: a position in time, kept as ISO text
                     "account": r["account"],          # nominal: a label, kept as text (leading zeros matter)
                     "category": r["category"],
                     "description": r["description"],
                     "amount": paise(r["amount"])})    # cardinal: a quantity, in whole paise
    return rows

def rupees(p):
    return f"₹{p // 100:,}.{p % 100:02d}"

rows = load(SAMPLE)
by_cat = {}
for r in rows:
    by_cat[r["category"]] = by_cat.get(r["category"], 0) + r["amount"]
for cat, total in sorted(by_cat.items(), key=lambda kv: -kv[1]):
    print(f"{cat:12} {rupees(total):>12}")
grand = sum(r["amount"] for r in rows)
print(f"{'total':12} {rupees(grand):>12}   ({len(rows)} entries)")
assert grand == sum(by_cat.values())                    # the categories partition the total
print("accounts seen:", sorted({r["account"] for r in rows}))
print("float total for comparison:", sum(float(r["amount"]) / 100 for r in rows))
Text
rent           ₹22,000.00
school         ₹15,000.00
groceries       ₹7,151.50
electricity     ₹1,254.00
transport         ₹500.00
total          ₹45,905.50   (8 entries)
accounts seen: ['00451200917', '30091877610']
float total for comparison: 45905.5

Step 4: reconcile. Compare the program's totals with yours, line by line. Where they differ, find out which is wrong before changing either: a misread amount, a line in the wrong category, a slip in a carry. Write down each cause; they're the commonest errors in real household accounts too.

Senior and architect lens

  • Representation is a decision. Amounts in integer paise are exact and add exactly; floats happen to give the right total for eight lines (the last line of output) but drift across thousands of operations and fail equality checks. Labels as text keep their leading zeros. These choices are the same ones a payments system makes, for the same reasons.
  • Invariants catch errors early. The assertion that category totals add up to the grand total is cheap and catches a whole class of bugs (a line counted twice, a category typo creating a phantom category). Every later stage adds invariants of its own.
  • Validation at the edge. paise() refuses anything that isn't an amount, so a stray "₹" or a comma in the CSV fails loudly at load time instead of producing a wrong total later.

Evidence

Keep these in your folder:

  • ledger.csv with at least one month (yours or the sample).
  • Your hand totals, photographed or typed.
  • ledger.py and its output, with the totals matching yours.
  • A note on each discrepancy you found and its cause.

Carry forward

Stage 2, after chapter 2, reads amounts and account labels written in other forms (lakh and crore, Western grouping, separators from bank exports in other formats) and converts them safely. Keep the ledger: every later stage reads it.