🚀 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.
- Deposits and withdrawals that raise errors on bad amounts
- History and statements with
__str__ - 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):ValueErrorifamount <= 0, otherwise add it tobalancewithdraw(amount):ValueErrorifamount <= 0,InsufficientFundsErrorif it's more than the balance, otherwise subtract it
Quiz
What does this print?
50 2
45 3
50 3
20 1
Example
Floats vs cents vs Decimal
Formatting only hides the error; cents and
Decimal avoid it entirely.
Exercise
Step 2: history and statements
- Start every account with an empty
historylist deposit/withdrawappend("deposit", amount)or("withdraw", amount)after they succeed__str__returns text like"Ana: 120.00"statement()returns one line per entry, then the balance:
+50.00 deposit
-30.00 withdraw
Balance: 120.00
Exercise
Step 3: transfers and savings
- Add
transfer(self, other, amount)toBankAccount: withdraw fromself, then deposit intoother. If the withdrawal fails, the error propagates and nothing changes. - Create
SavingsAccount(BankAccount)with__init__(self, owner, balance=0, rate=0.02)(callsuper().__init__) andadd_interest(): depositround(balance * rate, 2)if it's more than 0, and return the interest.