Recap: Account State
Lesson 37 of 48 in Coddy's Python for C 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.
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
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking7Structs to Python Objects
Allocation and Object LifetimeInitializing Object StateBound Methods Versus CallbacksShared State and ShadowingProperties and Validated StateRecap: Account State2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler