Python Morsels Exercise

Class representing a bank account with read-only balance

3 bonuses 7 hints 8 solutions 241 users solved 25 reviews

I'd like you to make a class that represents a bank account.

Your bank account should accept an optional balance argument (defaulting to 0), have a balance attribute, and have deposit, withdraw, and transfer methods:

>>> a1 = BankAccount()
>>> a1.balance
>>> a1.deposit(10)
>>> a1.balance
>>> a2 = BankAccount(balance=20)
>>> a2.withdraw(15)
>>> a2.balance
>>> a1.transfer(a2, 3)
>>> a1
>>> a2

Your bank account should also have a nice string representation (as shown above).

This example might not seem realistic (it's not) but it's a classic example for good reason:

  1. most real-world object-oriented programming in Python involves a lot of code (classes aren't usually worth the complexity until you have a sufficiently complex problem)
  2. a bank account is a pretty common and familiar concept which doesn't require a lot of domain-specific knowledge

Bonus 1

This is just a preview of the problem statement.

This exercise includes 3 bonuses and 7 hint links.

To solve this exercise, sign in to your Python Morsels account.

A learning habit for experienced Pythonistas

Profile picture of Trey

My name is Trey Hunner and I hold Python trainings for teams. I've spent countless hours refining my most interesting Python exercises into Python Morsels, a Python skill-building platform for folks who already know Python. Python Morsels is design to help you deepen your Python skills every week.

Sign up for Python Morsels to access this exercise and many more.

Join Python Morsels ✨