Bank Account

Bank Account

Write a BankAccount class.

BankAccount(balance=0)
  • __init__(self, balance=0) — stores balance as an attribute (self.balance).
  • deposit(self, amount) — adds amount to the balance.
  • withdraw(self, amount) — subtracts amount from the balance. If amount is greater than the current balance, raise ValueError("insufficient funds") instead, and leave the balance unchanged.

Examples

account = BankAccount()
account.deposit(100)
account.balance          // → 100
account.withdraw(30)
account.balance          // → 70
account.withdraw(1000)   // raises ValueError("insufficient funds")

Walkthrough

Thinking it through

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

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

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount

__init__ stores the starting balance as self.balance — an attribute that belongs to this specific account object, separate from any other BankAccount you might create.

deposit is unconditional — money can always be added, so it's a single +=.

withdraw needs the guard clause pattern from the exceptions section: check the failure condition first, and raise before making any changes, rather than subtracting and trying to "undo" it afterward. This is important — if you subtracted first and checked after, an over-withdrawal would leave self.balance in an incorrect (possibly negative) state even though the operation was supposed to have failed entirely. Checking first guarantees the balance is never touched at all when the withdrawal is rejected.

This combines two things from earlier in the course: attributes that persist on an object between method calls (self.balance set once, read and modified by later calls), and raising a specific exception with a clear message when an operation is invalid — same as the exceptions section, just now living inside a method instead of a standalone function.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.