Recap: Model a Bank Account
Lesson 37 of 48 in Coddy's Python for GDScript Developers course.
Challenge
BeginnerImplement Account(owner, balance), where the initial integer balance is nonnegative. Store independent instance state. Provide deposit(amount) and withdraw(amount), each returning the new balance. Reject nonpositive amounts and withdrawals greater than the balance with ValueError, preserving state. Provide __str__ as owner:balance. Input has two lines of owner balance, then a command count, then commands index action amount. Index is 0 or 1, action is deposit or withdraw, and owners contain no spaces. The driver prints each new balance or invalid, then both accounts in input order.
The locked driver reads input and prints results. Submit the required class and function definitions only; do not read input or print in your solution. Keep the API names exactly as specified.
Your code goes in the editable files account.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable 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 GDScript Developers
1From GDScript to Python
Run Your First Python ProgramPrint Is Not printsVar, Const, and BindingsInteger Division DifferencesSimilar Indentation, New ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and RebindingItems and enumerateWhile and Early ExitArray Callbacks and KeysRecap: Build a Ranking7Instances and Shared State
New and Python Class CallsInit and Per-instance ListsCallable and Bound MethodsStatic and Instance StateSetters and Printable ObjectsRecap: Model a Bank Account2Values and Decisions
Null and NoneThe is Keyword Changes MeaningLogical Results and OperandsConditional ExpressionsRecap: Eligibility Rules3Collections and Shared State
Array and List APIsArrays, Vectors, and TuplesDictionary Lookup RulesDuplicate and Shallow CopyRecap: Clean an Inventory6Input, Errors, and Modules
Console Work Outside GodotValidation and ExceptionsScript Resources and ImportsTyped GDScript and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler