Menu
CoddyTech

Recap: Account State

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

challenge icon

Challenge

Beginner

Implement Account(owner,balance) for a nonnegative initial integer balance, independent per instance. deposit(amount) and withdraw(amount) return the new balance; nonpositive amounts and overdrafts raise ValueError without mutation. __str__ returns owner:balance. The driver reads two owner/balance lines, a command count, and index/action/amount commands. Index is 0 or 1; action is deposit or withdraw; owners have no spaces. It prints each returned balance or invalid, then both accounts.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

Validate before state changes, just as a careful C status-returning API leaves its output unchanged on failure.

Your code goes in account.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

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 C Developers

Practice on your own: Online Python compiler