Pawan natekar
3 min readJul 16, 2024

intermediate Python project: Building a Simple Budget Tracker. This project will involve handling user inputs, storing data, and performing basic calculations to track expenses and incomes.

Created by pawan natekar

Project: Simple Budget Tracker

Features:
1. Add Income: Add a new income entry.
2. Add Expense: Add a new expense entry.
3. View Transactions: Display all income and expense transactions.
4. View Balance: Display the current balance.
5. Save and Load Transactions: Save transactions to a file and load them when the program starts.

Step-by-Step Guide

1. Define the Transaction Class

First, we will define a `Transaction` class to represent each income or expense entry. This class will include attributes like `amount`, `description`, and `type` (income or expense).

```python
class Transaction:
def __init__(self, amount, description, t_type):
self.amount = amount
self.description = description
self.type = t_type def __str__(self):
return f"{self.type.capitalize()}: ${self.amount:.2f} - {self.description}"
```

2. Define the BudgetTracker Class

Next, we will define a `BudgetTracker` class to manage the list of transactions. This class will handle adding incomes and expenses, viewing transactions, and calculating the balance.

```python
import json class BudgetTracker:
def __init__(self, filename="transactions.json"):
self.transactions = []
self.filename = filename
self.load_transactions() def add_transaction(self, amount, description, t_type):
transaction = Transaction(amount, description, t_type)
self.transactions.append(transaction)
self.save_transactions() def view_transactions(self):
for transaction in self.transactions:
print(transaction) def get_balance(self):
balance = 0
for transaction in self.transactions:
if transaction.type == "income":
balance += transaction.amount
elif transaction.type == "expense":
balance -= transaction.amount
return balance def save_transactions(self):
with open(self.filename, 'w’) as file: json_transactions = [transaction.__dict__ for transaction in self.transactions]
json.dump(json_transactions, file) def load_transactions(self):
try:
with open(self.filename, 'r’) as file: json_transactions = json.load(file)
self.transactions = [Transaction(**transaction) for transaction in json_transactions]
except FileNotFoundError:
pass
```

3. Create the Command-Line Interface

We will create a simple command-line interface to interact with our budget tracker application.

```python
def main():
budget_tracker = BudgetTracker() while True:
print("\nBudget Tracker:")
print("1. Add Income")
print("2. Add Expense")
print("3. View Transactions")
print("4. View Balance")
print("5. Exit") choice = input("Choose an option: ")if choice == '1’: amount = float(input("Enter income amount: "))
description = input("Enter income description: ") budget_tracker.add_transaction(amount, description, "income")
elif choice == '2’:
amount = float(input("Enter expense amount: "))
description = input("Enter expense description: ") budget_tracker.add_transaction(amount, description, "expense")
elif choice == '3’: budget_tracker.view_transactions()
elif choice == '4’:
balance = budget_tracker.get_balance()
print(f"Current Balance: ${balance:.2f}")
elif choice == '5’:
break
else:
print("Invalid choice. Please try again.") if __name__ == "__main__":
main()
```

Explanation:

- Transaction Class: Represents each income or expense entry with attributes for `amount`, `description`, and `type`.
- BudgetTracker Class: Manages the list of transactions. It includes methods for adding transactions, viewing transactions, calculating the balance, and saving/loading transactions from a file.
- Command-Line Interface: Provides a simple interface for the user to interact with the budget tracker. Users can add incomes, add expenses, view transactions, and view the balance.

Running the Application

To run the application, save the code in a Python file (e.g., `budget_tracker.py`) and execute it:

```bash
python budget_tracker.py
```

You can interact with the application through the command-line interface, and the transactions will be saved to a file (`transactions.json`) so that they persist between sessions.

This project helps solidify concepts like OOP, file handling, and creating a user interface in Python. Enjoy building and managing your budget!