DEV Community

JARED ARITO
JARED ARITO

Posted on

Master Python Collections by Building a Personal Expense Tracker

Master Python Collections by Building a Personal Expense Tracker

In our last tutorial, we explored how to handle single data inputs by building a currency converter. Today, we are taking our Python skills a step further. We will look at how programs handle collections of data by building a functional personal expense tracker.

Managing multiple data entries is a foundational skill in software engineering. In this guide, you will learn how to use Python lists, dictionaries, and loops to manage a running budget.

Prerequisites

  • Basic understanding of variables and the input() function.
  • A working Python environment (like VS Code or an online editor).

Step 1: Storing Data with Python Lists

When a user enters multiple expenses, we cannot store them in a single variable because each new input would overwrite the old one. Instead, we use a list. Think of a list as a blank sheet of paper where you can continuously write down entries one after the other.

Let's initialize an empty list to act as our ledger database:

# Create an empty list to store our data records
expense_ledger = []

print("System initialized. Expense ledger is empty and ready.")
Enter fullscreen mode Exit fullscreen mode

Step 2: Creating the Data Logic

An expense record is not just a single number; it requires a name (text description) and a cost (numeric value). To bundle these two related pieces of information together cleanly, we use a Python dictionary.

Once the dictionary entry is created, we use the .append() method to push that entire entry smoothly into our tracking list.

# Capture the name and cost from the user interface
item_name = input("Enter what you bought (e.g., Internet, Token): ")
item_cost = float(input(f"Enter the amount paid for {item_name} (KES): "))

# Bundle the variables into a structured dictionary layout
single_record = {"item": item_name, "cost": item_cost}

# Save the entry directly into our ledger list
expense_ledger.append(single_record)

print(f"Successfully recorded: {item_name} at KES {item_cost:,.2f}")
Enter fullscreen mode Exit fullscreen mode

Step 3: Summarizing the Total with Loops

To display the budget history and calculate a running total, the program needs to read through the list line by line. We achieve this using a for loop. The loop looks at each dictionary item, extracts the cost value, and continuously adds it to our total counter variable.

# Initialize a base counter tracking total spend
total_expenditure = 0.0

print("\n--- Current Expense Summary ---")

# Step through each recorded dictionary in the ledger list
for entry in expense_ledger:
    print(f"- {entry['item']}: KES {entry['cost']:,.2f}")
    total_expenditure += entry['cost']

print("-" * 31)
print(f"TOTAL AMOUNT SPENT: KES {total_expenditure:,.2f}")
Enter fullscreen mode Exit fullscreen mode

The Complete Continuous Script

To make the program highly functional, we can wrap our logic inside a while loop. This setup keeps the script running continuously, allowing you to add as many items as you want until you explicitly type exit.

Here is the complete script ready to copy, paste, and run in your VS Code workspace:

# Initialize the list ledger database
expense_ledger = []

print("=== KENYAN SHILLING EXPENSE TRACKER ===")

while True:
    print("\n[1] Add New Expense | [2] View Summary & Exit")
    choice = input("Select an option (1 or 2): ")

    if choice == "1":
        item_name = input("Enter expense item description: ")
        item_cost = float(input(f"Enter cost for '{item_name}' (KES): "))

        # Save record item entry
        expense_ledger.append({"item": item_name, "cost": item_cost})
        print(f"Record Saved: KES {item_cost:,.2f} spent on {item_name}.")

    elif choice == "2":
        total_expenditure = 0.0
        print("\n==============================")
        print("    FINAL BUDGET LEDGER       ")
        print("==============================")

        for entry in expense_ledger:
            print(f"• {entry['item']}: KES {entry['cost']:,.2f}")
            total_expenditure += entry['cost']

        print("------------------------------")
        print(f"TOTAL SPEND: KES {total_expenditure:,.2f}")
        print("==============================")
        print("Thank you for using the tracker system!")
        break
    else:
        print("Invalid option selection. Please enter 1 or 2.")
Enter fullscreen mode Exit fullscreen mode

Conclusion & Code Challenge

You have successfully scaled up your Python basics to handle arrays, dictionary pairings, and interactive loops!

Your Next Learning Challenge: Can you modify this loop system to add a safety alert threshold? Try checking if the calculated total_expenditure passes a budget limit of KES 20,000, and print a caution warning if it does! Share your updated code variations in the comments below.

Top comments (0)