ACCT 350 · Data Analytics for Accountants

A First Look at Programming for Accountants

A gentle first look at Python and SQL for accountants, showing how a few lines of code repeat and check work that a spreadsheet struggles with.

Key takeaways

  • A program is a precise list of steps, so it can repeat the same careful work on any amount of data without drift or fatigue.
  • Python is a general-purpose language that is good at reading files, cleaning data and calculating; SQL is a language for asking questions of databases.
  • Reading a short program is a lot like reading a recipe, and you can check one by tracing it with a small example by hand.
  • Code is worth it for tasks you repeat, for large data and for work that needs a record of every step.
  • Money needs care in code: use whole cents or exact decimal types, and test the results against totals you can trust.

Every month Dev does the same chore for Maya. He opens the bank's payment file, copies it into a spreadsheet, deletes the junk rows, sorts by vendor, adds up each vendor's payments and pastes the result into a report. It takes him ninety minutes. Last month he made a copy-paste slip, and one vendor's total was off by $400 for two weeks before anyone noticed.

A program is just a list of exact instructions that a computer follows. If Dev writes the steps once, the computer can repeat them in two seconds every month, the same way each time. It will not get tired at row 900, and it will never forget to delete the junk rows.

You do not need to become a software engineer to benefit. Accountants today use small amounts of code the way earlier accountants used the adding machine: as a tool for doing careful work fast. This lesson shows what that looks like. We will read two short pieces of code, trace them by hand, and talk about when code is the right tool and when a spreadsheet is better.

Why code, when we have spreadsheets?

Spreadsheets are wonderful. For a quick look at a small table, nothing beats one. But they have limits. Formulas hide in cells, so it is hard to see the whole logic at once. Clicking and dragging leave no record of what was done. Large files get slow, and a stray typed number can sit in the middle of a formula without anyone noticing.

Code fixes these problems in three ways. It is repeatable: run it again next month on the new file. It is visible: the steps are written down in order, so a colleague can read and review them. And it scales: the same ten lines work on 900 rows or 9 million. That matters for audit and tax work, where you may need to test every transaction, as in Analytics in Auditing, and for the cleaning steps in Getting and Cleaning Accounting Data.

There are many languages. Two are especially common in accounting work.

Python is a readable, general-purpose language. It reads files, cleans and reshapes data, does the math, draws charts and talks to other systems. Libraries, which are bundles of ready-made code, add extra powers, such as tools for handling tables.

SQL (often said "sequel," short for Structured Query Language) is the standard way to ask questions of a database, a place where data is stored in tables with rows and columns. The accounting software your company uses almost certainly keeps its records in one. SQL lets you say "give me this, from that, where this is true," and the database does the work.

Spreadsheet, SQL and Python
Spreadsheet Best for small tables and quick looks Easy to see and change numbers Steps are hidden in cells Hard to repeat exactly SQL Best for asking questions of stored data Short, readable questions Works on millions of rows Needs a database to ask Python Best for cleaning and multi-step work Reads almost any file Every step is written down Takes practice to learn Spreadsheet Best for small tables and quick looks Easy to see and change numbers Steps are hidden in cells Hard to repeat exactly SQL Best for asking questions of stored data Short, readable questions Works on millions of rows Needs a database to ask Python Best for cleaning and multi-step work Reads almost any file Every step is written down Takes practice to learn

Most accountants use all three. The skill is knowing which fits the job.

How to read a program

Programs have a few building blocks, and they all show up in everyday life.

  • A variable is a labeled box that holds a value, like writing "rent = 1200" on a sticky note.
  • A loop repeats a step for each item, like "for each invoice in the stack, do this."
  • A condition chooses between paths, like "if the amount is over $5,000, flag it."
  • A function is a named recipe you can reuse, like "add up this list."

With these four, you can read most short accounting programs. The trick is to trace one by hand with a tiny data set, writing down what each variable holds after each step.

The working loop of a programmer
Fix and extend Correct any mistake, then add the next small step. Check the result Compare to a total or sample you can verify by hand. Write a small step Do one thing, such as read the file and count the rows. Run it Let the computer follow the instructions. 1 2 3 4 Write a small step Do one thing, such as read the file and count the rows. 1 Run it Let the computer follow the instructions. 2 Check the result Compare to a total or sample you can verify by hand. 3 Fix and extend Correct any mistake, then add the next small step. 4

Even experts spend most of their time going around this circle.

Worked example: totaling payments by vendor

Dev has a file named payments.csv. A CSV file is plain text where each line is a row and commas separate the columns. Here is the whole file:

vendor,amount
FreshFarms,400
CupCo,150
FreshFarms,250
CupCo,90
Dairy,300

The goal is the total paid to each vendor. Here is a short Python program that does it. You do not have to write this yet, only to read it.

import csv

totals = {}
with open("payments.csv") as f:
    for row in csv.DictReader(f):
        vendor = row["vendor"]
        amount = float(row["amount"])
        totals[vendor] = totals.get(vendor, 0) + amount

for vendor, total in sorted(totals.items()):
    print(vendor, total)

Let's read it line by line, as if it were a recipe.

  1. import csv borrows a ready-made tool for reading CSV files.
  2. totals = {} makes an empty dictionary, a list of labeled boxes where each vendor name will point to a number. At the start it is empty.
  3. with open(...) opens the file. for row in csv.DictReader(f) is a loop: take each line after the header, one at a time, and call it row.
  4. Inside the loop, vendor gets the vendor's name, and amount gets the number, converted from text to a number with float.
  5. The key line is totals[vendor] = totals.get(vendor, 0) + amount. It reads: "look up this vendor's total so far, or use 0 if we have not met them yet, add this amount, and save it."
  6. The last loop prints each vendor in alphabetical order.

Now trace it with the five rows.

Row 1: FreshFarms 400   totals = {FreshFarms: 400}
Row 2: CupCo 150        totals = {FreshFarms: 400, CupCo: 150}
Row 3: FreshFarms 250   totals = {FreshFarms: 650, CupCo: 150}
Row 4: CupCo 90         totals = {FreshFarms: 650, CupCo: 240}
Row 5: Dairy 300        totals = {FreshFarms: 650, CupCo: 240, Dairy: 300}

The program prints the vendors in alphabetical order: CupCo 240.0, then Dairy 300.0, then FreshFarms 650.0. The check that matters comes next. The five payments add to 400 + 150 + 250 + 90 + 300 = 1,190, and the three totals add to 240 + 300 + 650 = 1,190. They agree, so nothing was dropped or doubled.

Payments by vendor, from the program
Maya's Smoothies Payments by Vendor Payment file, five rows Vendor totals CupCo $240 Dairy $300 FreshFarms $650 Total paid $1,190 Maya's Smoothies Payments by Vendor Payment file, five rows Vendor totals CupCo $240 Dairy $300 FreshFarms $650 Total paid $1,190

Example with made-up numbers.

The same question in SQL is shorter, if the payments sit in a database table named payments:

SELECT vendor, SUM(amount) AS total
FROM payments
GROUP BY vendor
ORDER BY vendor;

Read it as plain English: from the payments table, group the rows by vendor, add up the amounts in each group, and list the groups in alphabetical order. The answer is the same three lines. SQL is not better than Python. It is just the natural language for asking a database a question.

Habits that keep code honest

Good accountants and good programmers share the same virtues.

Check totals. You did it above: the sum of the parts must equal the sum of the whole. Build the check into the program so it complains out loud if the numbers do not match. A program that runs without errors can still be wrong.

Handle money carefully. Computers store many decimals in a way that is slightly off. In Python, adding 0.1 and 0.2 gives 0.30000000000000004. For money, use whole cents (store $12.34 as 1234) or an exact decimal type that the language provides.

Keep the raw data untouched. Never edit the original file. Read it, and write results to a new place, so you can always start again. This is the same idea as keeping the original source document behind a journal entry.

Write notes in the code. A short comment saying why you did something helps whoever reads it next, including you in six months.

Protect the data. Do not put passwords or client data in code that you share. Follow the rules in Data Types, Quality and Governance, and ask before you send any company data to an outside tool or service.

Have someone review it. A second pair of eyes catches mistakes, just as it does with a reconciliation.

A common mistake: code that runs but is wrong

The most common beginner error is to believe the output because the computer printed it. Suppose Dev's file had one vendor spelled "FreshFarms" in two rows and "Fresh Farms" in a third. The program would treat them as two vendors and the totals would split. Nothing would crash. The numbers would just be quietly wrong.

The cure is the same as for any analysis: look at the data first, clean names, test on a small sample you can check by hand, and compare totals to the ledger. Another common error is to use code where it is not needed. If you have 12 rows and need the answer once, a spreadsheet takes a minute. A good rule is to reach for code when the job repeats, when the data is large, or when you need an exact record of the steps.

Where to go from here

You do not have to learn everything at once. A sensible path is to get comfortable with spreadsheet functions and pivot tables, then learn basic SQL, then try Python on one chore you really do each month. Pick a task you hate and automate that. Real motivation beats any course. Use trusted documentation and your employer's approved tools, and remember that tools change, so check what your workplace allows before you install anything. Whatever you build, the output will go to a person, perhaps through a dashboard like those in Dashboards and Data Storytelling, and the person will still ask, "Is it right?"

Words to know

Program a precise list of instructions that a computer follows.

Python a readable general-purpose programming language that is popular for cleaning and analyzing data.

SQL a language for asking questions of data stored in a database.

Database an organized store of data in tables with rows and columns.

Loop a step that repeats once for each item in a list.

Dictionary a collection of labeled boxes, where each label points to a value.

CSV file a plain-text table in which each line is a row and commas separate the columns.

Check yourself

  1. Name two advantages of code over a spreadsheet for a monthly task.
  2. What is the difference between Python and SQL in what they are mostly used for?
  3. In the vendor program, what does totals.get(vendor, 0) do the first time a vendor appears?
  4. The five payments are 400, 150, 250, 90 and 300. What is each vendor's total, and what must the three totals add up to?
  5. Why should money often be stored in whole cents in code?
  6. Explain why a program that runs without errors can still give wrong answers.
Show the answers
  1. Code is repeatable and visible, since the same steps run exactly the same way each month and every step is written down for review; it also scales to much larger data.
  2. Python is a general-purpose language for reading, cleaning and calculating on data, while SQL is for asking questions of data stored in a database.
  3. It returns 0, since the vendor has no total yet, so the first amount is added to 0.
  4. FreshFarms 400 + 250 = 650, CupCo 150 + 90 = 240, Dairy 300; the totals must add to 650 + 240 + 300 = 1,190, the sum of all five payments.
  5. Computers store many decimals slightly inexactly (0.1 + 0.2 gives 0.30000000000000004), while whole cents are exact.
  6. The program follows its instructions exactly, so wrong inputs or wrong instructions, such as a vendor spelled two ways, give wrong results with no error message, and only a check against a trusted total reveals it.

A free self-study program written for 4Accounting with AI writing tools and not reviewed line by line by a person. It is not an accredited degree and awards no credit. Check anything you rely on against a textbook or primary source. Report an error.

In this unit: Applications

  1. Analytics in AuditingSee how auditors use data tools to test every transaction instead of a small sample, and how to turn flagged items into real evidence.11 min
  2. Analytics in Management AccountingSee how managers use data to explain cost changes, find which customers really earn money, and test what-if plans before spending.10 min
  3. Analytics in Tax WorkLearn how tax professionals use data to check sales tax, catch reporting gaps, compare book and tax numbers, and plan, all with human review.11 min
  4. Dashboards and Data StorytellingLearn how to turn numbers into a clear picture and a short story that a busy reader can understand and act on within a minute.11 min
  5. A First Look at Programming for AccountantsA gentle first look at Python and SQL for accountants, showing how a few lines of code repeat and check work that a spreadsheet struggles with.11 min

In the news