Bitpath

Boss lesson · Unit 07

A bank

Accounts, transfers and a history, with rules nobody can skip

12 exercisesabout 3 min

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?

Python
account = {"owner": "Ana", "balance": 100}
account["balance"] -= 500
print(account["balance"])

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.

Python
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 += amount

Concept

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.

Python
class NoFunds(Exception):
    pass

def pay(balance, price):
    if price > balance:
        raise NoFunds("too expensive")
    return balance - price

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy