Practice: Bank Account

Practice: Bank Account

This exercise combines state, methods, and raise — a class that protects its own rules.

Exercise

  1. Define a class named BankAccount.
  2. __init__ takes owner and stores it; it also sets a balance attribute to 0.
  3. Add a method named deposit with one parameter, amount. It adds amount to the balance. A zero or negative amount raises ValueError with the message amount must be positive.
  4. Add a method named withdraw with one parameter, amount. It subtracts amount from the balance. A zero or negative amount raises ValueError with the message amount must be positive; an amount above the balance raises ValueError with the message insufficient funds.
account = BankAccount("Ada")
account.deposit(100)
account.withdraw(30)
print(account.balance)

Output:

70

Run your code to see the output, then press Submit.

Hints

  • This is the withdraw function from the exceptions section, moved onto an object that owns the balance.
  • Check the amount before touching self.balance, so a rejected call leaves the state unchanged.

Tests

import unittest


class TestBankAccount(unittest.TestCase):
    def test_new_account_has_zero_balance(self):
        self.assertEqual(BankAccount("Ada").balance, 0)

    def test_owner_is_stored(self):
        self.assertEqual(BankAccount("Ada").owner, "Ada")

    def test_deposit_and_withdraw(self):
        account = BankAccount("Ada")
        account.deposit(100)
        account.withdraw(30)
        self.assertEqual(account.balance, 70)

    def test_negative_deposit_raises(self):
        with self.assertRaises(ValueError):
            BankAccount("Ada").deposit(-10)

    def test_overdraw_raises_and_preserves_balance(self):
        account = BankAccount("Ada")
        account.deposit(50)
        with self.assertRaises(ValueError):
            account.withdraw(80)
        self.assertEqual(account.balance, 50)
class BankAccount:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        self.balance += amount

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount


account = BankAccount("Ada")
account.deposit(100)
account.withdraw(30)
print(account.balance)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.