Skip to content
Exercise · Classes · lesson 10 of 11

Exercise: bank account

Write a class BankAccount, a bank account:

  • the call BankAccount(owner, balance=0) stores the owner's name in the attribute owner and the starting balance in the attribute balance;
  • the method deposit(self, amount) adds amount to the balance;
  • the method withdraw(self, amount) takes amount out of the account and returns True; if the account holds less than amount, it returns False and leaves the balance unchanged.

Examples:

  • BankAccount("Ann").balance → 0
  • acc = BankAccount("Ann", 50), then acc.withdraw(20) → True, and acc.balance → 30
  • after that, acc.withdraw(40) → False, and acc.balance is still 30

Constraints: amounts are non-negative integers; withdrawing exactly the whole balance works; each account has its own balance.

In the tests, getattr(acc, "balance", None) reads acc.balance, or gives None if there is no such attribute.

Do not add extra imports unless the task says so explicitly.

account.py — python
python · 10 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way