Skip to contentSkip to navigation

Module 12 · Lesson 03

Project: OOP Bank Account System

Model a small bank with classes: accounts that keep a transaction history, a family of exceptions for refused operations, savings and current accounts with their own rules, and safe transfers.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Guard the balance
  • A family of bank errors
  • Account types with their own rules
  • Watch a withdrawal get refused

The bank in four parts

Each account guards its own balance. Every change goes through a checked method and is written down.

  • The base account

    Account holds an owner, a balance and a history list.

  • Checked changes

    deposit() and withdraw() check the amount before they touch the balance.

  • A family of errors

    InsufficientFunds and InvalidAmount both inherit from BankError.

  • Account types

    Savings and Current inherit from Account and change only the rules that differ.

Accounts everywhere

Anything with a balance that must never go wrong follows these rules.

  • Banking appsEvery payment is a checked withdrawal with a line in the statement.
  • Game walletsCoins and gems follow the same rule: no spending what you do not have.
  • Gift cardsThe balance goes down with each purchase and never below zero.
  • Booking systemsSeats are booked and released only through checked methods.

Refusing a withdrawal

This line stops a withdrawal that would go below zero. Tap each part to see its job.

Part 1 of 3

Tap any part of the code below, or press Next.1 of 3 explored

raise:Stops the withdrawal before anything has changed.

Build the bank in five steps

Build the project one step at a time. Each example runs on its own: change it, then press Run.

Example 1 of 61. The account

The account starts with an owner, a balance and an empty history.

Your turn: Make a second account with no starting balance and print it.

Python
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
        self.history = []

    def __str__(self):
        return f"{self.owner}: ${self.balance:.2f}"

acc = Account("Ana", 50)
print(acc)
print(acc.history)
Output
Press Run to see what it prints.

Watch a withdrawal get refused

Press Step to run one line at a time. `acc.balance` is the balance stored on the account.

Ready. Press Step to run the first line.

  1. class Account:
  2. def __init__(self, balance):
  3. self.balance = balance
  4. def withdraw(self, amount):
  5. if amount > self.balance:
  6. return "refused"
  7. self.balance -= amount
  8. return "ok"
  9. acc = Account(30)
  10. print(acc.withdraw(20))
  11. print(acc.withdraw(20))
  12. print(acc.balance)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Spending more than you have:

class Purse:
    def __init__(self):
        self.coins = 5
    def spend(self, n):
        if n <= self.coins:
            self.coins -= n
p = Purse()
p.spend(8)
print(p.coins)

0 of 6 answered

Common bank account misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Building the bank

The brief

Every account has an owner, a balance and a history of transactions. Customers can deposit and withdraw, and money can be transferred between accounts. A current account may go overdrawn down to an agreed limit. A savings account may never go below zero, earns interest, and allows only three withdrawals a month. Any refused operation must raise an exception that says exactly why, and must leave every balance untouched.

The exception family

Start with the ways things can go wrong, because the rest of the design depends on them:

Try it 1: edit me, then Run
class BankError(Exception):
    pass

class InvalidAmountError(BankError):
    pass

class InsufficientFundsError(BankError):
    pass

class LimitReachedError(BankError):
    pass
Output
Press Run to see what it prints.

A caller who only wants to show a friendly message can catch BankError. A caller who wants to offer an overdraft when funds are short can catch InsufficientFundsError on its own.

The base account

Try it 2: edit me, then Run
class Account:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self._balance = 0.0
        self.history = []
        if balance:
            self.deposit(balance)

    @property
    def balance(self):
        return self._balance
Output
Press Run to see what it prints.

The balance is stored as _balance, with a leading underscore, as a signal that only the class's own methods should change it. The @property line, which the Python in Depth course explains fully, lets callers read account.balance like a normal attribute but not assign to it. Even the opening balance goes through deposit, so it is checked and appears in the history.

Checked changes and a history

Try it 3: edit me, then Run
    def _check_amount(self, amount):
        if amount <= 0:
            raise InvalidAmountError(f"amount must be positive, got {amount}")

    def deposit(self, amount):
        self._check_amount(amount)
        self._balance = round(self._balance + amount, 2)
        self.history.append(("deposit", amount, self._balance))

    def available(self):
        return self._balance

    def withdraw(self, amount):
        self._check_amount(amount)
        if amount > self.available():
            raise InsufficientFundsError(f"{self.owner} can withdraw at most {self.available():.2f}")
        self._balance = round(self._balance - amount, 2)
        self.history.append(("withdraw", amount, self._balance))
Output
Press Run to see what it prints.

Notice the order inside withdraw: every check happens before anything changes. If a check fails, the exception leaves the method with the balance and history exactly as they were. Getting this order right is the most important habit in the whole project.

available() answers "how much may be taken out?". In the base class that is just the balance, but subclasses will change the answer without touching withdraw at all.

Subclasses with their own rules

Try it 4: edit me, then Run
class Current(Account):
    def __init__(self, owner, balance=0.0, overdraft=100.0):
        super().__init__(owner, balance)
        self.overdraft = overdraft

    def available(self):
        return self._balance + self.overdraft

class Savings(Account):
    max_withdrawals = 3

    def __init__(self, owner, balance=0.0, rate=0.02):
        super().__init__(owner, balance)
        self.rate = rate
        self.withdrawals = 0

    def withdraw(self, amount):
        if self.withdrawals >= Savings.max_withdrawals:
            raise LimitReachedError("only 3 withdrawals a month")
        super().withdraw(amount)
        self.withdrawals += 1

    def add_interest(self):
        interest = round(self._balance * self.rate, 2)
        if interest > 0:
            self.deposit(interest)
Output
Press Run to see what it prints.

Current only overrides available, and the inherited withdraw automatically allows the overdraft. Savings extends withdraw: it checks its own limit, then hands over to the parent with super(), and only counts the withdrawal after the parent succeeded. Each subclass contains only what is different.

A safe transfer

A transfer is a withdrawal from one account and a deposit into another. If the withdrawal fails, nothing must have been deposited:

Try it 5: edit me, then Run
def transfer(source, target, amount):
    source.withdraw(amount)     # raises before any money moves if refused
    target.deposit(amount)
Output
Press Run to see what it prints.

Because withdraw raises before changing anything, and the deposit only runs after it succeeded, a refused transfer leaves both accounts unchanged. Real banks use database transactions for the same guarantee.

Statements

The history makes a statement easy: loop over it and format each entry. Printing balances with :.2f and amounts right-aligned turns raw tuples into something a customer can read. Because the history is a list of plain tuples, it could also be saved to CSV or JSON exactly as in the earlier projects.

Interest and the month end

add_interest deposits the interest through deposit, so it is recorded in the history like any other credit and goes through the same checks. A month-end routine for a whole bank is then a loop over every account: savings accounts add their interest, and the withdrawal counter goes back to zero. Because each kind of account knows its own rules, the loop does not need to check types; it can call a month_end() method that the parent defines as doing nothing and Savings overrides.

Testing as you build

Check each rule with one good case and one bad case: a deposit and a negative deposit, a withdrawal within the balance and one beyond it, an overdraft just inside and just outside the limit, a fourth savings withdrawal, and a transfer that fails. After every refused operation, check that the balance did not change. The Lab tasks below walk the same path.

Syntax

The general shape of the statements in this lesson.

syntax.py
class BankError(Exception): pass
class InsufficientFundsError(BankError): pass
self._balance                         # internal: change via methods
def withdraw(self, amount):
    check(amount)                     # every check first
    self._balance -= amount           # then change state
    self.history.append(("withdraw", amount, self._balance))
class Savings(Account):
    def withdraw(self, amount):
        ...                           # own rule
        super().withdraw(amount)      # then the parent's
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Accounts in action

Intermediate

Build the account family, run a series of operations including refused ones, and show each account's balance afterwards.

Python
class BankError(Exception):
    pass

class InsufficientFundsError(BankError):
    pass

class LimitReachedError(BankError):
    pass

class Account:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self.balance = balance

    def available(self):
        return self.balance

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

class Current(Account):
    def __init__(self, owner, balance=0.0, overdraft=100.0):
        super().__init__(owner, balance)
        self.overdraft = overdraft

    def available(self):
        return self.balance + self.overdraft

class Savings(Account):
    def __init__(self, owner, balance=0.0):
        super().__init__(owner, balance)
        self.withdrawals = 0

    def withdraw(self, amount):
        if self.withdrawals >= 3:
            raise LimitReachedError("only 3 withdrawals a month")
        super().withdraw(amount)
        self.withdrawals += 1

ana = Current("Ana", 50.0)
ben = Savings("Ben", 500.0)
steps = [(ana, 120), (ana, 40), (ben, 50), (ben, 50), (ben, 50), (ben, 50), (ben, -5)]
for account, amount in steps:
    try:
        account.withdraw(amount)
        print(f"{account.owner} took {amount}, balance {account.balance:.2f}")
    except BankError as error:
        print(f"Refused ({type(error).__name__}): {error}")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Ana's current account goes overdrawn to -70.00, then the next withdrawal would pass the 100 overdraft, so it is refused. Ben's fourth withdrawal hits the savings limit before any money moves. One except BankError handles every refusal, and the exception's class name says which rule was broken.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Changing the balance before checking

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
def withdraw(self, amount):
    self.balance -= amount
    if self.balance < 0:
        raise BankError('insufficient funds')
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

The exception is raised, but the balance has already gone negative and stays that way

Write this instead

def withdraw(self, amount):
    if amount > self.balance:
        raise BankError('insufficient funds')
    self.balance -= amount

Why it happens

The state changed before the check, so raising afterwards cannot undo it.

In the real world

Where this shows up in software people use every day.

  1. Prepaid cards for a school canteen

    Education services

    A school gives each pupil a prepaid canteen card. Parents top cards up, the till charges meals, and staff cards are allowed a small negative balance until payday. A daily report lists every refused payment.

    Why Python fits

    The staff card only overrides limit, and the shared pay method applies it, exactly like the overdraft in the main project. Mo's second meal is refused before the balance changes, and the refusal is recorded for the daily report rather than stopping the till.

    Python
    class CardError(Exception):
        pass
    
    class Card:
        def __init__(self, holder, balance=0.0):
            self.holder = holder
            self.balance = balance
    
        def limit(self):
            return 0.0
    
        def pay(self, amount):
            if self.balance - amount < -self.limit():
                raise CardError(f"{self.holder}: balance {self.balance:.2f}, meal {amount:.2f}")
            self.balance = round(self.balance - amount, 2)
    
    class StaffCard(Card):
        def limit(self):
            return 10.0
    
    cards = {"Mo": Card("Mo", 4.0), "Lin": Card("Lin", 12.0), "Mr Ode": StaffCard("Mr Ode", 2.0)}
    refused = []
    for holder, meal in [("Mo", 3.2), ("Lin", 3.2), ("Mo", 3.2), ("Mr Ode", 3.2)]:
        try:
            cards[holder].pay(meal)
        except CardError as error:
            refused.append(str(error))
    
    for card in cards.values():
        print(f"{card.holder:<7}{card.balance:>6.2f}")
    print("Refused:", refused)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why use exceptions instead of returning False?

A returned False is easy to ignore, and the money would silently not move. An exception forces the caller to deal with the refusal or stop.

Should balances be floats?

This project rounds to two places, which is fine for learning. Real banking software stores whole cents as integers or uses the decimal module, so amounts like 0.10 are exact.

How would the accounts be saved?

The same way as the expense tracker: write each account's owner, type and history to a file, CSV or JSON, and rebuild the objects by replaying the history through deposit and withdraw when loading.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 11 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.