Recap: Model a Bank Account
Lesson 37 of 48 in Coddy's Python for Rust 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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking7Instances and Shared State
Structs to InstancesInitialization and Ownershipself and Bound MethodsClass and Instance StateProperties and DisplayRecap: Model a Bank Account2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler