← Previous Module 8: Classes & Objects Next →
Statement
Solution

Python Exercise 8.2: Bank Account System

Classes are perfect for modelling real-world systems. Build a BankAccount class that manages deposits, withdrawals, and balance checks with proper validation.

Your class should:

  • Define a class called BankAccount.
  • Include an __init__ method that accepts an owner name and an optional balance (default 0).
  • Include a deposit(amount) method that adds the amount to the balance. Print a confirmation message. Reject deposits of 0 or less.
  • Include a withdraw(amount) method that deducts the amount. Reject withdrawals that exceed the current balance or are 0 or less, printing an appropriate message each time.
  • Include a get_balance() method that prints the current balance.
  • Demonstrate the class with a series of transactions as shown below.

Sample Interaction:

Input
Output
(None)
Deposited $500. New balance: $500 Deposited $200. New balance: $700 Withdrew $150. New balance: $550 Error: Insufficient funds. Balance for Alice: $550

Solution

Each method validates its input before modifying the balance, keeping the object in a consistent state at all times.

class BankAccount: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def deposit(self, amount): if amount <= 0: print("Error: Deposit amount must be positive.") return self.balance += amount print(f"Deposited ${amount}. New balance: ${self.balance}") def withdraw(self, amount): if amount <= 0: print("Error: Withdrawal amount must be positive.") return if amount > self.balance: print("Error: Insufficient funds.") return self.balance -= amount print(f"Withdrew ${amount}. New balance: ${self.balance}") def get_balance(self): print(f"Balance for {self.owner}: ${self.balance}") # Demo account = BankAccount("Alice") account.deposit(500) account.deposit(200) account.withdraw(150) account.withdraw(1000) account.get_balance()

Key Concepts:

  • Default parameter values (e.g. balance=0) make arguments optional.
  • Guard clauses with return exit a method early when validation fails.
  • Instance attributes (self.balance) persist across all method calls on the same object.
  • Methods can both modify state and communicate results via print().
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top