Python for beginners: Build a locale-aware expense tracker

Python is a programming language used to automate tasks, work with data and build applications. Start by running a short program, then build an expense tracker that handles international text, dates and amounts without guessing what the input means.

You do not need programming experience. You need a computer, permission to install software and a plain text editor. Python includes a standard library, a collection of tools that comes with the language.

1. Install Python and run a program

Follow the official Python beginner's guide to install Python. Open a terminal, an application where you type commands, and check the installation:

text
python3 --version

If that command is not found, try py --version or the command given in your installation instructions. Reopen the terminal after installation if necessary.

Create a practice folder. In a plain text editor, save this program as hello.py:

python
print("Hello!")
print("Illustrative name: Åsa")

Run it from a terminal in the same folder:

text
python3 hello.py

Use py instead of python3 if that is the command that worked on your computer. You should see both lines. If Python cannot find the file, check the terminal's current folder and make sure the file is named hello.py, not hello.py.txt.

print() displays a value. Text inside quotation marks is a string. For the remaining examples, save each code block as a .py file and run it in the same way.

2. Store values and make decisions

A variable gives a value a name. Try changing these illustrative values:

python
description = "Train ticket"
amount = 12
paid = True

print(description)
print(amount + 3)
print(paid)
print(type(amount))

amount is an integer, or whole number. paid is a Boolean: it is either True or False. type() shows the kind of value Python received.

Python also has floating-point numbers, such as 12.5. They are useful for many calculations, but cannot represent every decimal fraction exactly. For money, the tracker uses Decimal instead.

To accept input and choose what happens next, try:

python
category = input("Enter a category: ").strip().lower()

if category == "travel":
    print("This is a travel expense.")
elif category == "food":
    print("This is a food expense.")
else:
    print("This is another kind of expense.")

input() returns text. strip() removes spaces at its ends, and lower() makes it lowercase. The indented lines belong to the condition above them. == compares values; a single = assigns one.

Normalizing a category can make matching easier. Do not automatically apply the same change to a person's name.

3. Repeat work and organize data

A list holds a sequence of values. A loop visits each value:

python
categories = ["travel", "food", "housing"]

for category in categories:
    print(category)

A function packages work for reuse. It can accept an argument and return a result:

python
def make_label(category):
    return "Expense category: " + category

print(make_label("travel"))
print(make_label("food"))

The tracker also uses dictionaries, which store values under keys. For example, {"category": "travel", "amount": "12.50"} associates each value with a descriptive key. A list of these dictionaries can represent several expenses.

4. Keep dates and amounts unambiguous

A date such as 03/04/2026 can mean different things to different readers. For entry and storage, the tracker requires the exact form YYYY-MM-DD:

python
import re
from datetime import date

text = input("Enter a date as YYYY-MM-DD: ").strip()

try:
    if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", text):
        raise ValueError("Use YYYY-MM-DD.")
    expense_date = date.fromisoformat(text)
    print("Stored date:", expense_date.isoformat())
except ValueError as error:
    print("Invalid date:", error)

The pattern checks the shape; date.fromisoformat() checks that the date exists. Both checks matter because the latter also accepts other ISO date forms. try and except let the program report invalid input without a traceback.

Amounts need an agreement too. 1,234 may represent a grouped whole number or a decimal amount. A locale describes conventions used for presentation and interpretation. The tracker uses Babel, a Python package that accepts an explicit locale without changing the whole process's locale.

Install it in your practice environment:

text
python3 -m pip install Babel

If you use py to run Python, use py -m pip install Babel instead. Save this illustrative example as amounts.py:

python
from decimal import Decimal
from babel.numbers import format_currency, parse_decimal

for loc, text in [("en", "1,234.50"), ("fr", "1 234,50")]:
    amount = parse_decimal(text, locale=loc, strict=True)
    print(loc, amount)
    print(format_currency(amount, "XXX", locale=loc,
                          decimal_quantization=False))

The space in the second amount is a narrow no-break space; copy it with the example. Both inputs represent the same decimal value, but their separators differ. XXX is an illustrative currency placeholder. The displayed symbol and spacing depend on the locale.

Formatting is not conversion. A locale determines presentation; it does not tell the program an exchange rate or make unlike currency amounts safe to add.

5. Read and write international text

Files store text as bytes. An encoding tells a program how to turn those bytes back into characters. Specify UTF-8 when working with your own text files:

python
message = "Illustrative name: Åsa"

with open("example.txt", "w", encoding="utf-8") as file:
    file.write(message)

with open("example.txt", "r", encoding="utf-8") as file:
    print(file.read())

"w" replaces the existing file. with closes it when the block finishes. Specifying UTF-8 when reading does not repair a file saved in a different encoding; you need to know its original encoding or obtain a correctly encoded copy.

6. Build an expense tracker

This command-line project stores expenses in JSON, prints monthly totals by currency and category, and exports entries to CSV. It uses explicit Babel locales: en and fr are language-based examples, not an exhaustive list of formats.

Save the following as expenses.py in your practice folder:

python
import argparse
import csv
import json
import re
from datetime import date
from decimal import Decimal, InvalidOperation

from babel.numbers import NumberFormatError, format_currency, parse_decimal

def parse_date(text):
    if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", text):
        raise ValueError("Date must use YYYY-MM-DD.")
    return date.fromisoformat(text).isoformat()

def parse_amount(text, loc):
    try:
        value = parse_decimal(text, locale=loc, strict=True)
    except NumberFormatError as error:
        raise ValueError(f"Invalid amount for locale {loc}.") from error

    # This exercise accepts at most two decimal places.
    if (not value.is_finite() or value < 0
            or value.as_tuple().exponent < -2
            or value.adjusted() > 12):
        raise ValueError("Use a non-negative amount with at most two decimals.")
    return value

def load_entries(path):
    try:
        with open(path, encoding="utf-8") as file:
            return json.load(file)
    except FileNotFoundError:
        return []

def main():
    parser = argparse.ArgumentParser(description="Practice expense tracker")
    parser.add_argument("--locale", choices=["en", "fr"], default="en")
    parser.add_argument("--file", default="expenses.json")
    commands = parser.add_subparsers(dest="command", required=True)

    commands.add_parser("add")
    summary = commands.add_parser("summary")
    summary.add_argument("month", help="Month in YYYY-MM form")
    export = commands.add_parser("export")
    export.add_argument("output", help="CSV output filename")
    args = parser.parse_args()

    try:
        entries = load_entries(args.file)

        if args.command == "add":
            description = input("Description: ").strip()
            category = input("Category: ").strip()
            currency = input("Currency code: ").strip().upper()
            day = parse_date(input("Date (YYYY-MM-DD): ").strip())
            amount = parse_amount(
                input(f"Amount ({args.locale} format): ").strip(),
                args.locale,
            )

            if not description or not category:
                raise ValueError("Description and category are required.")
            if not re.fullmatch(r"[A-Z]{3}", currency):
                raise ValueError("Use a three-letter currency label.")

            entries.append({
                "description": description,
                "category": category,
                "currency": currency,
                "date": day,
                "amount": str(amount),
            })
            with open(args.file, "w", encoding="utf-8") as file:
                json.dump(entries, file, ensure_ascii=False, indent=2)
            print("Saved.")

        elif args.command == "summary":
            parse_date(args.month + "-01")
            totals = {}
            for item in entries:
                if item["date"].startswith(args.month + "-"):
                    key = (item["currency"], item["category"])
                    totals[key] = totals.get(key, Decimal("0")) + Decimal(
                        item["amount"]
                    )

            if not totals:
                print("No entries for this month.")
            for (currency, category), total in sorted(totals.items()):
                formatted = format_currency(
                    total, currency, locale=args.locale,
                    currency_digits=False, decimal_quantization=False,
                )
                print(f"{currency} | {category}: {formatted}")

        else:
            fields = ["date", "description", "category", "currency", "amount"]
            with open(args.output, "w", encoding="utf-8", newline="") as file:
                writer = csv.DictWriter(file, fieldnames=fields)
                writer.writeheader()
                writer.writerows(entries)
            print(f"Exported to {args.output}.")

    except (ValueError, InvalidOperation, OSError, UnicodeError) as error:
        parser.error(str(error))

if __name__ == "__main__":
    main()

Run these commands from the folder containing the script:

text
python3 expenses.py --locale en add
python3 expenses.py --locale en summary 2026-04
python3 expenses.py export expenses.csv

For an illustrative entry, use Train, category travel, currency label XXX, date 2026-04-03 and amount 12.50. Run add again with --locale fr and enter 12,50 to try a different decimal convention. Select the locale before add or summary in the command.

The program stores each amount as decimal text, not a floating-point number. Summaries keep categories and currency labels separate. The two-decimal limit is a teaching simplification, not a rule for every currency. The program checks the shape of a currency label, not whether it is valid.

Files are created in the terminal's current folder. Invalid JSON stops the program rather than silently replacing the file. CSV export overwrites its output file. Treat CSV from untrusted sources carefully: spreadsheet applications may interpret some cell contents as formulas.

This is a learning exercise, not accounting or tax software. It does not convert currencies, protect sensitive data or provide safe backups.

7. Debug locale and encoding failures

Start with the last line of a traceback, then inspect the named file and line. A SyntaxError often points to a missing quote, colon or bracket; an IndentationError points to spacing at the start of a line. Change one thing, save and run again.

Babel uses its own locale data. Python's standard-library locale module instead depends on settings and locales available on the system. To inspect those settings, run this diagnostic:

python
import locale
import os
import sys

for name in ("LC_ALL", "LC_NUMERIC", "LC_TIME", "LANG"):
    print(name, "=", repr(os.environ.get(name)))

print("Terminal output encoding:", sys.stdout.encoding)
try:
    print("Environment locale:", locale.setlocale(locale.LC_ALL, ""))
    print("Decimal separator:", locale.localeconv()["decimal_point"])
except locale.Error as error:
    print("Locale unavailable:", error)

If setlocale() reports an unavailable locale, inspect the variables printed above. LC_ALL, when set, overrides the other locale categories. Check which locale names your system provides; on systems with a locale command, locale -a lists installed options. Install or generate the needed locale using your system's instructions, or select an available name. Names differ across operating systems.

If the locale works but text fails, distinguish a file error from a terminal error. For UnicodeDecodeError, trace the open() call and identify the file's actual encoding. If reading works but printing fails, inspect the terminal output encoding and its settings. Replacing bad characters can hide the problem rather than fix the data.

8. Treat practice data as private by design

Expense descriptions can identify someone or reveal sensitive details. Use invented entries, and keep expenses.json and exported CSV files out of a public repository.

The GDPR is a regional data-protection regulation. Its scope can extend beyond the region in specified circumstances; processing information about someone there does not automatically mean every organization is covered. Personal data includes information that identifies someone directly or indirectly.

Where it applies, start with a specific purpose and collect only what is necessary for it. Identify a lawful basis for processing; consent is one possible basis, not a universal requirement. Limit retention, restrict access and be able to explain your decisions. Replacing names with identifiers can reduce exposure, but data that can still be linked to people remains personal data.

Before sending data across borders or using a provider that processes it elsewhere, establish where it will go and check the applicable transfer rules and safeguards. Code alone cannot establish compliance. For an individual legal question, consult a qualified privacy professional.

9. Choose a path and show your work

Choose your next project based on the work you enjoy. For web development, build an API that validates input and returns translated messages. For data work, load a CSV, clean it and explain your results; SQL for beginners is a useful next step. For automation, package a repeatable task and test its failure cases. If machine learning interests you, first practise Python, data cleaning and evaluation on a small dataset.

Whatever path you choose, publish a project with invented data, instructions to run it, tests and a candid limitations section. Explain a decision you made, such as why the tracker stores amounts separately by currency, and how you checked it. Use the Python foundations guide to assess the language's trade-offs and the skills-first career strategy to present your evidence.

The members' bonus adds internationalization techniques, privacy patterns, automated tests and a Dockerfile for this project.