Recap: Model a Bank Account
Lesson 37 of 48 in Coddy's Python for Lua 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 Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking7Classes Beyond Metatables
Tables to Class InstancesConstructors and Fresh StateColon Calls to Bound MethodsLookup and Shared DefaultsProperties and tostringRecap: Model a Bank Account2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler