Recap: Account State
Lesson 37 of 48 in Coddy's Python for Java 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. Port Java encapsulated-model habits using Python instance state and the documented exception contract.
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 Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking7Instance and Class State
Instances Without newInitializing Instance StateBound Methods and selfClass State Is Not a FieldProperties and Access ControlRecap: Account State2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler