Build a bank account class with validated deposits and withdrawals.
What You Will Learn
An account object encapsulates a balance and exposes methods for changing it through checked operations. This learning example uses integer cents to avoid binary floating-point issues; a real banking application needs persistence, concurrency control, auditing, and authorization.
This is a classroom model, not a safe or complete financial transaction system.
Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
class BankAccount:
def __init__(self, opening_balance_cents=0):
if opening_balance_cents < 0:
raise ValueError("Opening balance cannot be negative")
self.balance_cents = opening_balance_cents
def deposit(self, amount_cents):
if amount_cents <= 0:
raise ValueError("Deposit must be positive")
self.balance_cents += amount_cents
def withdraw(self, amount_cents):
if amount_cents <= 0 or amount_cents > self.balance_cents:
raise ValueError("Invalid withdrawal")
self.balance_cents -= amount_cents
account = BankAccount(2000)
account.deposit(500)
account.withdraw(700)
print(account.balance_cents)
How the Example Works
- The class BankAccount groups data and behavior; its methods run when called on an instance.
- The variable account holds the result of BankAccount(2000). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression account.balance_cents prints 1800. Compare that result with the rule above before you change the argument.
Expected output from the example:
1800
When You Would Use This
A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.
Practice: Modify the Code
Add a transaction history for a small practice account.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Using float values for money without addressing precision and rounding.
- Allowing negative deposits or withdrawals beyond the available balance.
Key Takeaways
- Build a bank account class with validated deposits and withdrawals.
- An account object encapsulates a balance and exposes methods for changing it through checked operations.
- This is a classroom model, not a safe or complete financial transaction system.