Recap: Independent Accounts
Lesson 37 of 48 in Coddy's Python for C# Developers course.
Challenge
BeginnerImplement 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
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking7Objects and Properties
Instances Across ModulesInitialize Instance StateBound Methods and selfClass and Instance AttributesProperties and Access RulesRecap: Independent Accounts2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler