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
Accountholds an owner, a balance and a history list.Checked changes
deposit()andwithdraw()check the amount before they touch the balance.A family of errors
InsufficientFundsandInvalidAmountboth inherit fromBankError.Account types
SavingsandCurrentinherit fromAccountand 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
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.
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)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.
- class Account:
- def __init__(self, balance):
- self.balance = balance
- def withdraw(self, amount):
- if amount > self.balance:
- return "refused"
- self.balance -= amount
- return "ok"
- acc = Account(30)
- print(acc.withdraw(20))
- print(acc.withdraw(20))
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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'sPress 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
Build the account family, run a series of operations including refused ones, and show each account's balance afterwards.
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}")Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
def withdraw(self, amount):
self.balance -= amount
if self.balance < 0:
raise BankError('insufficient funds')Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Education services
Prepaid cards for a school canteen
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 sharedpaymethod 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.Pythonclass 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)OutputPress 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?
Should balances be floats?
How would the accounts be saved?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.