Menu
CoddyTech

Recap: Independent Accounts

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

challenge icon

Challenge

Beginner

Implement Account(owner, balance) with independent state and a nonnegative initial integer balance. deposit(amount) and withdraw(amount) return the resulting balance. Reject nonpositive amounts and overdrafts with ValueError before mutation. __str__ returns owner:balance. The driver reads two owner/balance lines, a command count, and commands index action amount. Index is 0 or 1 and action is deposit or withdraw; owners have no spaces. It prints each result or invalid, then both accounts in input order.

C# transfer checkpoint

As with separate C# reference objects, separately constructed Python accounts must not share mutable state.

C# reference excerpt: executable statements assume using System; type-only excerpts illustrate the declared contract.

var left = new System.Collections.Generic.List<int> { 5 };
var right = new System.Collections.Generic.List<int> { 5 };
left[0] += 2;
Console.WriteLine(right[0]);

Python pattern

left = [5]
right = [5]
left[0] += 2
print(right[0])

Editable implementation files: account.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation 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 C# Developers

Practice on your own: Online Python compiler