Lesson 83 +45 XP

Project 7: Bank Account Class

Project 7: Bank Account Class

Build a BankAccount class with deposit, withdraw, and balance methods, then use it from main.

The goal

A class that starts with a balance, lets money in and out safely, and reports the current balance.

What you practice

  • Classes and __init__
  • Methods
  • Encapsulation with an underscore
  • if guards

Starter code

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount

    def withdraw(self, amount):
        if 0 < amount <= self._balance:
            self._balance -= amount
        else:
            print("Withdrawal rejected")

    def balance(self):
        return self._balance

account = BankAccount("Ada", 100)
account.deposit(50)
account.withdraw(30)
print(account.balance())  # 120

Step-by-step

  1. Run the starter and confirm 120 prints.
  2. Try withdrawing more than the balance; it must be rejected.
  3. Try a negative deposit; it must be ignored.
  4. Add a str method so printing the account is friendly.

Checklist

  • [ ] __init__ sets the balance
  • [ ] deposit guards against bad amounts
  • [ ] withdraw can't overdraw
  • [ ] balance() reports the total
  • [ ] The class works from main

TL;DR

  • __init__ sets up each account.
  • Guards inside methods keep the data safe.
  • The single underscore marks internal data.