#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.ValueError('amount must be positive').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.
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
First solves only, ranked by stars and then time.