Editor

A Bank Account That Says No

#578 · Errors and exceptions · Intermediate · 60 XP · about 10 min

Write a class Account that refuses bad requests by raising an exception, and leaves the balance untouched when it does:

  • Account(owner, balance=0) stores owner and balance as attributes.
  • deposit(amount) adds amount and returns the new balance.
  • withdraw(amount) takes amount out and returns the new balance.
  • An amount of 0 or less, for either method, raises ValueError('amount must be positive').
  • A withdrawal of more than the balance raises InsufficientFunds with the message 'Mia has 100, cannot withdraw 150', using the owner, the balance and the amount.

InsufficientFunds is provided. Taking out the whole balance is allowed.

Examples

acct = Account('Mia', 100)
acct.withdraw(30)   # returns 70
acct.deposit(5)     # returns 75
acct.withdraw(150)  # raises InsufficientFunds: Mia has 75, cannot withdraw 150
acct.balance        # still 75
acct.deposit(-5)    # raises ValueError: amount must be positive

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.