Python Classes & Objects
💡
Exercise 37

Bank Accounts 20 XP Medium

Ctrl+Enter Run Ctrl+S Save

Encapsulation means keeping data safe inside the object. Methods control how data is accessed and modified.

class BankAccount: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount > self.balance: print('Insufficient funds!') else: self.balance -= amount
📋 Instructions
Create a `BankAccount` class with: - `__init__(self, owner, balance=0)` - `deposit(amount)` — adds to balance, prints new balance - `withdraw(amount)` — subtracts if sufficient funds - `get_balance()` — returns the balance Test: ```python acc = BankAccount('Alice', 1000) acc.deposit(500) acc.withdraw(200) acc.withdraw(2000) print(f'Balance: ${acc.get_balance()}') ``` Expected output: ``` Deposited $500. New balance: $1500 Withdrew $200. New balance: $1300 Insufficient funds! Balance: $1300 ```
Create a BankAccount class with __init__(self, owner, balance=0). Add methods deposit(amount) and withdraw(amount). Check if enough balance before withdrawing!
⚠️ Try solving it yourself first — you'll learn more!
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            print('Insufficient funds!')
        else:
            self.balance -= amount
🧪 Test Cases
Input
Run your code
Expected
Deposited $500. New balance: $1500 Withdrew $200. New balance: $1300 Insufficient funds! Balance: $1300
Expected program output
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.