Recap: Account State
Lesson 37 of 48 in Coddy's Python for Go Developers course.
Challenge
BeginnerImplement 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. Transfer Go model invariants while using independent Python instance state and raised ValueError for rejection.
Editable files: account.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
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.
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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking7Structs to Python Classes
From Structs to InstancesInitialization and Fresh StateReceivers and Bound MethodsClass State and ShadowingProperties and Display HooksRecap: Account State2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler