Skip to content
Python project #10Intermediate

Bank Account System

Savings and current accounts with a minimum balance, an overdraft, transfers, monthly interest and statements — using inheritance and exact Decimal money.

Estimated time
~4 hours to build
Files
4 files · 369 lines
Technologies
Python 3, decimal.Decimal, Inheritance, Custom exceptions

Introduction

Banking is the textbook example of inheritance: every account deposits and withdraws, but savings and current accounts have different limits. This project models that with a base class and two subclasses, and uses Decimal so paise are never lost to rounding.

Problem statement

Open savings accounts (opening deposit and minimum balance ₹1,000) and current accounts (overdraft up to ₹5,000). Support deposits, withdrawals, transfers between accounts, a monthly interest run for savings accounts at a given annual rate, per-account statements and a summary of all accounts. Reject unknown account types and ids, insufficient funds, more than two decimal places and non-numbers.

Objectives

  • Use inheritance and method overriding
  • Represent money with decimal.Decimal
  • Design an exception hierarchy
  • Keep a transaction history per object

Features

  • SavingsAccount with a minimum balance and interest
  • CurrentAccount with an overdraft
  • Transfers that never half-complete
  • Statements with running balances
  • Validation of amounts with Decimal

Concepts demonstrated

  • Inheritance and polymorphism
  • Exact money arithmetic
  • Exception hierarchies
  • Encapsulated state

System architecture

Account implements deposit, withdraw and history; withdraw checks the balance against limit(), which subclasses override (₹1,000 for savings, −₹5,000 for current). SavingsAccount.add_interest adds one month's interest rounded half-up to the paisa. Bank creates accounts by type and performs transfers by withdrawing first, so a failed withdrawal leaves both accounts unchanged. BankError is the base exception and InsufficientFunds a subclass shown as 'Declined'.

Folder structure

TextProject tree
bank-account-system/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

196 lines
Pythonmain.py
"""Bank Account System: savings and current accounts with transfers, interest and statements.
Commands:
open savings|current <id> <name> <opening-deposit>
deposit <id> <amount>
withdraw <id> <amount>
transfer <from-id> <to-id> <amount>
interest <annual-rate-%> adds one month's interest to every savings account
statement <id>
accounts
quit
Money is handled with Decimal so paise are exact.
"""
import sys
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
PAISE = Decimal("0.01")
class BankError(Exception):
"""Base class for all banking errors."""
class InsufficientFunds(BankError):
pass
class AccountNotFound(BankError):
pass
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
def money(text: str) -> Decimal:
try:
value = Decimal(text.replace(",", ""))
except InvalidOperation:
raise BankError(f"'{text}' is not an amount") from None
if value <= 0 or value != value.quantize(PAISE):
raise BankError("amounts must be positive with at most two decimals")
return value
def rs(value: Decimal) -> str:
return f"Rs {value:,.2f}"
class Account:
kind = "account"
def __init__(self, number: str, owner: str, opening: Decimal):
self.number, self.owner = number, owner
self.balance = Decimal("0")
self.history: list[tuple[str, Decimal, Decimal]] = []
self.deposit(opening, "opening deposit")
def limit(self) -> Decimal:
"""The lowest balance this account may reach."""
return Decimal("0")
def _record(self, description: str, amount: Decimal) -> None:
self.balance += amount
self.history.append((description, amount, self.balance))
def deposit(self, amount: Decimal, description: str = "deposit") -> None:
self._record(description, amount)
def withdraw(self, amount: Decimal, description: str = "withdrawal") -> None:
if self.balance - amount < self.limit():
available = self.balance - self.limit()
raise InsufficientFunds(f"{self.number}: only {rs(max(available, Decimal(0)))} available")
self._record(description, -amount)
def __str__(self) -> str:
return f"{self.number:<6}{self.kind:<9}{self.owner:<8}{rs(self.balance):>15}"
class SavingsAccount(Account):
kind = "savings"
MINIMUM = Decimal("1000")
def limit(self) -> Decimal:
return self.MINIMUM
def add_interest(self, annual_rate: Decimal) -> Decimal:
interest = (self.balance * annual_rate / 100 / 12).quantize(PAISE, rounding=ROUND_HALF_UP)
if interest > 0:
self._record(f"interest @ {annual_rate}% p.a.", interest)
return interest
class CurrentAccount(Account):
kind = "current"
OVERDRAFT = Decimal("5000")
def limit(self) -> Decimal:
return -self.OVERDRAFT
class Bank:
TYPES = {"savings": SavingsAccount, "current": CurrentAccount}
def __init__(self):
self.accounts: dict[str, Account] = {}
def get(self, number: str) -> Account:
try:
return self.accounts[number.upper()]
except KeyError:
raise AccountNotFound(f"no account {number}") from None
def open(self, kind: str, number: str, owner: str, opening: Decimal) -> Account:
if kind not in self.TYPES:
raise BankError("account type must be savings or current")
if number.upper() in self.accounts:
raise BankError(f"account {number} already exists")
if kind == "savings" and opening < SavingsAccount.MINIMUM:
raise BankError(f"savings accounts need an opening deposit of at least {rs(SavingsAccount.MINIMUM)}")
account = self.TYPES[kind](number.upper(), owner, opening)
self.accounts[account.number] = account
return account
def transfer(self, src: str, dst: str, amount: Decimal) -> None:
a, b = self.get(src), self.get(dst)
if a is b:
raise BankError("can't transfer to the same account")
a.withdraw(amount, f"transfer to {b.number}") # raises before anything changes if funds are short
b.deposit(amount, f"transfer from {a.number}")
def run(bank: Bank, words: list[str]) -> None:
command = words[0].lower()
if command == "open":
account = bank.open(words[1].lower(), words[2], words[3], money(words[4]))
print(f"Opened {account.kind} account {account.number} for {account.owner}: {rs(account.balance)}")
elif command == "deposit":
account = bank.get(words[1])
account.deposit(money(words[2]))
print(f"{account.number}: deposited {rs(money(words[2]))}, balance {rs(account.balance)}")
elif command == "withdraw":
account = bank.get(words[1])
account.withdraw(money(words[2]))
print(f"{account.number}: withdrew {rs(money(words[2]))}, balance {rs(account.balance)}")
elif command == "transfer":
amount = money(words[3])
bank.transfer(words[1], words[2], amount)
print(f"Transferred {rs(amount)} from {words[1].upper()} to {words[2].upper()}")
elif command == "interest":
rate = Decimal(words[1].rstrip("%"))
for account in bank.accounts.values():
if isinstance(account, SavingsAccount):
print(f"{account.number}: interest {rs(account.add_interest(rate))}")
elif command == "statement":
account = bank.get(words[1])
print(f"Statement for {account.number} ({account.kind}, {account.owner})")
for description, amount, balance in account.history:
print(f" {description:<26}{amount:>+12,.2f}{balance:>14,.2f}")
elif command == "accounts":
for account in bank.accounts.values():
print(f" {account}")
print(f" Net balance of all accounts: {rs(sum((a.balance for a in bank.accounts.values()), Decimal(0)))}")
else:
raise BankError("unknown command")
def main() -> None:
bank = Bank()
print("Bank Account System")
while True:
line = ask("> ")
if line is None or line.lower() == "quit":
break
if not line:
continue
try:
run(bank, line.split())
except InsufficientFunds as error:
print(f"Declined: {error}")
except BankError as error:
print(f"Error: {error}")
except (IndexError, InvalidOperation):
print("Error: missing or invalid arguments")
if __name__ == "__main__":
main()

What each file does

main.py
The Account base class, the savings and current subclasses, the Bank service and the command loop.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Bank Account System
> open savings S1 Asha 25000
Opened savings account S1 for Asha: Rs 25,000.00
> open current C1 Ravi 3000
Opened current account C1 for Ravi: Rs 3,000.00
> open savings S2 Meera 500
Error: savings accounts need an opening deposit of at least Rs 1,000.00
> open fixed F1 Kiran 1000
Error: account type must be savings or current
> deposit S1 4999.50
S1: deposited Rs 4,999.50, balance Rs 29,999.50
> withdraw S1 28500
S1: withdrew Rs 28,500.00, balance Rs 1,499.50
> withdraw S1 2000
Declined: S1: only Rs 499.50 available
> withdraw C1 7500
C1: withdrew Rs 7,500.00, balance Rs -4,500.00
> withdraw C1 600
Declined: C1: only Rs 500.00 available
> transfer S1 C1 10000
Declined: S1: only Rs 499.50 available
> transfer C1 S1 400
Transferred Rs 400.00 from C1 to S1
> transfer C1 S9 100
Error: no account S9
> deposit S1 12.345
Error: amounts must be positive with at most two decimals
> deposit S1 abc
Error: 'abc' is not an amount
> interest 6%
S1: interest Rs 9.50
> statement S1
Statement for S1 (savings, Asha)
opening deposit +25,000.00 25,000.00
deposit +4,999.50 29,999.50
withdrawal -28,500.00 1,499.50
transfer from C1 +400.00 1,899.50
interest @ 6% p.a. +9.50 1,909.00
> statement C1
Statement for C1 (current, Ravi)
opening deposit +3,000.00 3,000.00
withdrawal -7,500.00 -4,500.00
transfer to S1 -400.00 -4,900.00
> accounts
S1 savings Asha Rs 1,909.00
C1 current Ravi Rs -4,900.00
Net balance of all accounts: Rs -2,991.00
> quit
Input
open savings S1 Asha 25000
open current C1 Ravi 3000
open savings S2 Meera 500
open fixed F1 Kiran 1000
deposit S1 4999.50
withdraw S1 28500
withdraw S1 2000
withdraw C1 7500
withdraw C1 600
transfer S1 C1 10000
transfer C1 S1 400
transfer C1 S9 100
deposit S1 12.345
deposit S1 abc
interest 6%
statement S1
statement C1
accounts
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • A savings account with ₹500 and a 'fixed' account type are rejected.
  • Withdrawing ₹2,000 from S1 is declined because only ₹499.50 is above the minimum balance.
  • C1 can go to −₹4,500 but not further than −₹5,000; one month of 6% interest on ₹1,899.50 is ₹9.50.

Common errors

0.1 + 0.2 style rounding errors in balances

Use Decimal for money and quantize to two places.

A transfer debits one account but not the other

Do the risky step (withdraw) first; deposit only if it succeeds.

Possible improvements

  • Add fixed-deposit accounts with maturity dates
  • Persist accounts to SQLite
  • Add monthly service charges for current accounts

Additional challenges

  1. 1Add an 'undo last transaction' command.
  2. 2Limit savings withdrawals to five per month.
  3. 3Print a statement only between two dates.

Built and tested it yourself? Mark it to update your dashboard.