Boss lesson · Unit 07
A bank
Accounts, transfers and a history, with rules nobody can skip
What you practise
- Accounts, transfers and a history, rules enforced by methods and exceptions
- A first design reviewed and improved
Try a question from this lesson
Pick one
A bank account as a plain dictionary. Nothing here checks anything. What does this program show?
account = {"owner": "Ana", "balance": 100}
account["balance"] -= 500
print(account["balance"])Correct answer
-400
Why
A dictionary holds whatever you put in it, so the balance drops to -400 without complaint. Any line anywhere in the program can do this. The rule "you cannot spend what you do not have" needs to live somewhere nobody can skip.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Rules live with the data
Put the balance in a class, and change it only through methods.
Each method checks its rule first and raises an error when the rule is broken. Now there is one place where money goes in and one where it goes out, and both are guarded.
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("bad amount")
self.balance += amountConcept
An error of your own
ValueError is a class, and you can make a child of it or of Exception: your own kind of error, with a name that says what went wrong.
Callers can then catch exactly this problem and nothing else.
class NoFunds(Exception):
pass
def pay(balance, price):
if price > balance:
raise NoFunds("too expensive")
return balance - price9 more exercises in the app
- 1× fill the blanks
- 3× type the answer
- 1× order the lines
- 3× multiple choice
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.