Python Code Example: Bank Account

A bank account is a real-world entity that has attributes such as an account holder’s name, balance, and account number. It also supports actions like depositing and withdrawing money.

In this example, we will create a BankAccount class in Python that includes:
Attributes: Account holder name and balance
Methods: Deposit, withdraw, and display balance
Encapsulation: Ensuring safe balance management

This example demonstrates object-oriented programming (OOP) by encapsulating data (balance, account holder) and behavior (transactions) in a structured way.


Python Code Example

class BankAccount:
    """Class to simulate a bank account with deposit and withdrawal functionality."""

    def __init__(self, account_holder, balance=0.0):
        """Constructor to initialize account holder and balance."""
        self.account_holder = account_holder
        self.balance = balance

    def deposit(self, amount):
        """Method to deposit money into the account."""
        if amount > 0:
            self.balance += amount
            print(f"Deposited ${amount:.2f}. New balance: ${self.balance:.2f}")
        else:
            print("Deposit amount must be positive.")

    def withdraw(self, amount):
        """Method to withdraw money from the account."""
        if 0 < amount <= self.balance:
            self.balance -= amount
            print(f"Withdrew ${amount:.2f}. New balance: ${self.balance:.2f}")
        elif amount > self.balance:
            print("Insufficient funds.")
        else:
            print("Withdrawal amount must be positive.")

    def display_balance(self):
        """Method to display the current balance."""
        print(f"Account Holder: {self.account_holder}, Balance: ${self.balance:.2f}")

# Creating a bank account for John Doe with an initial balance of $1000
account = BankAccount("John Doe", 1000.0)

# Performing transactions
account.display_balance()
account.deposit(500)
account.withdraw(300)
account.withdraw(1500)  # Should trigger "Insufficient funds"

Expected Output

Account Holder: John Doe, Balance: $1000.00
Deposited $500.00. New balance: $1500.00
Withdrew $300.00. New balance: $1200.00
Insufficient funds.

Code Explanation

  1. Defining the BankAccount class
    • The class contains an __init__ method that initializes the account holder and balance.
  2. Creating deposit() method
    • Checks if the deposit amount is positive and updates the balance.
  3. Creating withdraw() method
    • Ensures that the withdrawal amount is within available balance.
    • Prevents negative or overdraft transactions.
  4. Creating display_balance() method
    • Displays the account holder name and current balance.
  5. Creating and testing an account
    • A BankAccount object is created with an initial balance.
    • Transactions like deposit and withdrawal are performed.

This example demonstrates OOP principles like encapsulation and data management, making the bank account secure, reusable, and scalable! 🚀