Skip to content
Tutorials Center
My learning

Topics

Lesson 135 of 149 ยท Projects

Project: Banking System

Build a banking system in Python step by step. Use classes, inheritance, Decimal money, custom exceptions, transaction history and safe transfers, then test it with unittest.

A bank is a perfect project for practicing object-oriented programming. There are clear things (accounts, transactions, a bank), clear rules (you cannot withdraw more than you have), and clear failures (insufficient funds, unknown account). In this project you'll build a small banking system that uses most of what you have learned about classes: classes and objects, inheritance, properties, custom exceptions, data classes and Decimal for exact money.

The program grows in five stages, and each one is complete and runnable. By the end you'll have checking and savings accounts, a transaction history, transfers that never lose money halfway, and automated tests.

This is a teaching project. A real banking system needs databases, concurrency control, audit trails and regulation compliance that are far beyond this lesson. Never use code like this to handle real money.

Stage 1: money and exceptions

Never store money in a float. Binary floating point cannot represent a value like 0.10 exactly, so errors creep into your totals (see Decimal and Fractions). Use Decimal and round to cents in one place.

Then decide how failures will be reported. Custom exceptions give each failure a name that callers can catch precisely. Put them in a small hierarchy under one base class, so a caller can catch any banking problem with one except BankError.

Python Stage 1: money helper and exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice Decimal(str(value)). Converting through str avoids inheriting the float's tiny error, so 0.1 becomes exactly 0.10. The from None hides the confusing chained InvalidOperation traceback from the user. The exceptions carry data too: InsufficientFundsError stores the balance and the requested amount, so a caller can show a helpful message instead of parsing text.

Stage 2: an account that guards its own balance

A good class protects its own rules. Nobody outside should be able to set balance = 1_000_000. So the balance is stored in a private attribute, exposed through a read-only property, and changed only by methods that check the rules.

Each change is recorded as a transaction. A frozen data class is ideal: a record of the past must not change.

Python Stage 2: Account and Transaction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The most important line is the order inside withdraw: validate first, then change the balance, then record. If validation raises, nothing has been modified, so the account is never left half-updated. This "check before you change" habit is what makes the transfer in stage 4 safe.

Stage 3: inheritance for account types

A checking account and a savings account are both accounts, but they follow different rules. A checking account may allow an overdraft (a limited negative balance); a savings account pays interest and can be limited in withdrawals. Inheritance lets each subclass reuse Account and override only what differs.

To make that work cleanly, the base class asks one overridable question, "what is the lowest balance allowed?", instead of hard-coding zero. This pattern is called a hook method.

Python Stage 3: CheckingAccount and SavingsAccount

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

withdraw is written once, in the base class, and it automatically respects each subclass's rule because it asks self.minimum_balance(). That is polymorphism: the same call behaves differently depending on the object. If you later add a StudentAccount, you override one method and nothing else changes. The OOP principles lesson explains why this design is easier to extend than a chain of if account_type == ... checks.

Stage 4: the bank and safe transfers

A bank owns the accounts and does the jobs that involve more than one of them. The classic one is a transfer: take money from one account and put it in another. The danger is failure in the middle. If the withdrawal succeeds but the deposit fails, money has vanished.

The bank solves this the same way as stage 2: do every check that can fail before changing anything, and if a later step fails anyway, undo the earlier one.

Python Stage 4: Bank with accounts and transfers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

After every attempt, successful or not, the total stays at 600.00. That is the property a banking system must never break, so it is a good thing to check in a test. The "frozen target" case is the interesting one: the withdrawal had already happened when the deposit failed, and the except block put the money back before re-raising the error so the caller still hears about the failure.

Stage 5: testing the rules

Rules like "total money never changes" and "no negative amounts" are exactly what automated tests are for. Python's built-in unittest can run in the editor. assertRaises checks that the right exception appears, and a test for the total checks the invariant.

Python Stage 5: unittest for the bank

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

setUp gives every test fresh accounts, so tests cannot affect each other. The overdraw test checks the absence of side effects, which matters as much as the error itself. On your own machine you would save these tests in a file and run python -m unittest, or use pytest.

Ideas to extend it

  1. Persistence. Save accounts and history to JSON (see JSON) or SQLite (see sqlite3) and load them at start-up. Store Decimal values as strings, never floats.
  2. Statements. Print a monthly statement with the transactions between two dates, using datetime arithmetic.
  3. A command-line interface. Wrap the bank in a menu loop, or with argparse as in Command-Line Programs.
  4. Daily limits. Reject withdrawals that exceed a daily total, by summing today's transactions in history.
  5. Interest scheduler. Use add_monthly_interest() on every savings account at month end.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the project use Decimal instead of float for money?

    Binary floating point stores approximations of values like 0.1. Decimal stores them exactly, which is what financial code needs.
  2. 2. What is the advantage of a hierarchy of exceptions under BankError?

    A shared base class gives callers a choice: broad (BankError) or precise (InsufficientFundsError).
  3. 3. In withdraw, why is the balance checked before it is changed?

    Validate first, then mutate. That keeps failed operations free of side effects.
  4. 4. How does CheckingAccount allow an overdraft without rewriting withdraw?

    This hook-method pattern is polymorphism: withdraw asks self.minimum_balance(), and each subclass answers differently.
  5. 5. Why does transfer roll back the withdrawal when the deposit fails?

    Without the rollback, money withdrawn from the sender would vanish. The bank must keep the total unchanged even when a step fails.

Summary

  • Use Decimal for money, convert through str, and round in one helper.
  • A custom exception hierarchy (BankError and its subclasses) names each failure and lets callers catch it broadly or precisely.
  • Protect a class's rules: private attribute, read-only property, and methods that validate before changing.
  • Record history with a frozen data class and return copies so the past cannot be edited.
  • Inheritance and hook methods (minimum_balance) let subclasses vary behavior without duplicating code.
  • A Bank coordinates accounts. Multi-step operations such as transfers must roll back on failure so invariants (like the total) always hold.
  • Test the rules, including the absence of side effects after a failure, with unittest and assertRaises.

Next: Project: Inventory Manager, where you'll model a shop's stock with classes and save it as JSON.