Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Projects
  3. Build a Bank Account Manager with Classes

Project 9 · Guided build

Build a Bank Account Manager with Classes

Design a small banking model with accounts, deposits, withdrawals, custom exceptions, and a transaction history.

Open the compilerWarm-up exercises
intermediate90–120 minutesclassesexceptionsencapsulationlists
On this page
  1. What you will build
  2. The exception
  3. The class
  4. Why not expose balance directly?
  5. History
  6. Using the class
  7. Multiple accounts
  8. A text menu
  9. Testing checklist
  10. Stretch goals

This project applies classes and exceptions to a familiar domain. You will build an account model, enforce valid transactions, and keep a readable history.

What you will build#

A BankAccount class that supports:

  • An owner name and an opening balance.
  • deposit(amount) and withdraw(amount).
  • A custom InsufficientFundsError.
  • A transaction history with one entry per successful change.
  • A clear string representation.

A second function creates two accounts, performs a few operations, and prints the results.

The exception#

Python
class InsufficientFundsError(Exception):
    """Raised when a withdrawal exceeds the available balance."""

Create a specific exception instead of returning False or printing inside the method. The caller can then decide whether to show a message, retry, or stop.

The class#

Python
class BankAccount:
    def __init__(self, owner, balance=0.0):
        if not owner.strip():
            raise ValueError("Owner name is required")
        if balance < 0:
            raise ValueError("Opening balance cannot be negative")

        self.owner = owner.strip()
        self.balance = float(balance)
        self.history = []

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")

        self.balance += amount
        self.history.append(("deposit", amount))
        return self.balance

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("Withdrawal must be positive")
        if amount > self.balance:
            raise InsufficientFundsError(
                f"{self.owner} has only {self.balance:.2f} available"
            )

        self.balance -= amount
        self.history.append(("withdraw", amount))
        return self.balance

    def __repr__(self):
        return f"BankAccount(owner={self.owner!r}, balance={self.balance:.2f})"

The !r conversion in the f-string uses repr() for the owner, so quotes are included. That makes the output valid-looking Python.

Why not expose balance directly?#

Python does not enforce private attributes, but a leading underscore signals that a name is internal:

Python
class Account:
    def __init__(self, balance=0):
        self._balance = balance

    @property
    def balance(self):
        return self._balance

A read-only property lets callers inspect the balance without assigning to it. Changing money should happen through deposit() and withdraw(), which enforce the rules.

For this project, a plain public balance is acceptable. If you add a property, keep the method names consistent.

History#

The history stores tuples of (action, amount):

Python
def print_statement(self):
    print(f"Statement for {self.owner}")
    print(f"Opening balance: {self._opening_balance:.2f}")

    for index, (action, amount) in enumerate(self.history, start=1):
        print(f"{index:>2}. {action:<8} {amount:.2f}")

    print(f"Closing balance: {self.balance:.2f}")

Store the opening balance in __init__ if you want the statement to show it. Otherwise, start the statement with the first transaction.

Do not store a separate running total for each entry unless you need it; recomputing is simple and avoids inconsistent data.

Using the class#

Python
account = BankAccount("Ada", 100)

try:
    account.deposit(50)
    account.withdraw(30)
    account.withdraw(500)
except ValueError as error:
    print("Invalid amount:", error)
except InsufficientFundsError as error:
    print("Declined:", error)

print(account)
account.print_statement()

Only one error is caught per try block because the first exception jumps to a handler. If you want each operation to continue independently, wrap each call in its own try/except.

Multiple accounts#

Python
accounts = {
    "ada": BankAccount("Ada", 100),
    "grace": BankAccount("Grace", 250),
}

accounts["ada"].deposit(25)

for account in accounts.values():
    print(account)

A dictionary keyed by a short username makes lookups easy. If accounts can be renamed, do not use the name as both identity and display data.

A text menu#

If you want a full program, add a menu with create, deposit, withdraw, statement, and quit. Validate account names and amounts. Remember that ILoveCompiler supplies input in advance, so write the sequence of actions on separate lines and trace the prompts.

Testing checklist#

  • Create an account with a negative opening balance.
  • Deposit a positive amount and check the balance.
  • Attempt a zero or negative deposit.
  • Withdraw more than the balance and catch the custom error.
  • Withdraw the exact balance.
  • Print the statement and confirm every successful transaction appears once.
  • Verify the representation includes the owner and formatted balance.

Money and floats

This project uses floats to keep the focus on classes. Real banking systems use integer minor units or decimal arithmetic with explicit rounding rules. Do not present the model as production banking software.

Stretch goals#

  • Add a transfer(from_account, to_account, amount) function that rolls back if the deposit fails.
  • Add interest with apply_interest(rate).
  • Freeze an account and reject transactions while frozen.
  • Add a transaction timestamp.
  • Save accounts as JSON and reload them with validation.
Previous projectBuild a Weather Data Analyzer in PythonNext projectBuild a File Organizer Plan in Python

On this page

  1. What you will build
  2. The exception
  3. The class
  4. Why not expose balance directly?
  5. History
  6. Using the class
  7. Multiple accounts
  8. A text menu
  9. Testing checklist
  10. Stretch goals

Project checklist

  • Read the requirements.
  • Plan the data model.
  • Build one feature at a time.
  • Test invalid input.
  • Refactor after it works.