Menu
CoddyTech

Recap: Model a Bank Account

Lesson 37 of 48 in Coddy's Python for JavaScript Developers course.

challenge icon

Challenge

Beginner

Implement Account(owner, balance), where the initial integer balance is nonnegative. Store independent instance state. Provide deposit(amount) and withdraw(amount), each returning the new balance. Reject nonpositive amounts and withdrawals greater than the balance with ValueError, preserving state. Provide __str__ as owner:balance. Input has two lines of owner balance, then a command count, then commands index action amount. Index is 0 or 1, action is deposit or withdraw, and owners contain no spaces. The driver prints each new balance or invalid, then both accounts in input order.

The locked driver reads input and prints results. Submit the required class and function definitions only; do not read input or print in your solution. Keep the API names exactly as specified.

Your code goes in the editable files account.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable modules.

Try it yourself

from account import Account

accounts = []
for _ in range(2):
    owner, amount = input().split()
    accounts.append(Account(owner, int(amount)))
for _ in range(int(input())):
    index, action, amount = input().split()
    account = accounts[int(index)]
    try:
        if action == "deposit":
            print(account.deposit(int(amount)))
        else:
            print(account.withdraw(int(amount)))
    except ValueError:
        print("invalid")
for account in accounts:
    print(account)

All lessons in Python for JavaScript Developers

Practice on your own: Online Python compiler