Project: bank account

Mini Projects, lesson 5 of 6

🚀 Mini Projects, lesson 5 of 6

Project: bank account

Design a class with validation, custom errors, history and a subclass.

12 min

3 exercises

1 quiz

0/4 solved

Getting Python ready… examples can run in a moment.

This project combines classes and exceptions. A bank account must never reach an invalid state: no negative deposits, no withdrawing more than you have.

  1. Deposits and withdrawals that raise errors on bad amounts
  2. History and statements with __str__
  3. Transfers and savings with interest (inheritance)
Example

Using an account safely

Two exception types let the caller react differently to "declined" and "invalid". Try withdrawing exactly the balance.

Exercise

Step 1: deposit and withdraw

Complete the methods:

  • deposit(amount): ValueError if amount <= 0, otherwise add it to balance
  • withdraw(amount): ValueError if amount <= 0, InsufficientFundsError if it's more than the balance, otherwise subtract it
Quiz

What does this print?

Example

Floats vs cents vs Decimal

Formatting only hides the error; cents and Decimal avoid it entirely.

Exercise

Step 2: history and statements

  1. Start every account with an empty history list
  2. deposit/withdraw append ("deposit", amount) or ("withdraw", amount) after they succeed
  3. __str__ returns text like "Ana: 120.00"
  4. statement() returns one line per entry, then the balance:
+50.00 deposit
-30.00 withdraw
Balance: 120.00
Exercise

Step 3: transfers and savings

  1. Add transfer(self, other, amount) to BankAccount: withdraw from self, then deposit into other. If the withdrawal fails, the error propagates and nothing changes.
  2. Create SavingsAccount(BankAccount) with __init__(self, owner, balance=0, rate=0.02) (call super().__init__) and add_interest(): deposit round(balance * rate, 2) if it's more than 0, and return the interest.