Bank Account
Completed
Create BankAccount with deposit(amount), withdraw(amount) (print insufficient funds instead of going negative) and a balance attribute. Process commands like deposit 50 and withdraw 20, then print the final balance.
Input
Line 1: n. Then n commands.
Output
Any error messages, then balance: B.
Example
Input
4 deposit 100 withdraw 30 withdraw 100 deposit 5
Output
insufficient funds balance: 75
Editor
Python
Hints
Methods change the object's state through self.
getattr(obj, "deposit") fetches a method by name.
Solution explanation
Objects bundle data (the balance) with the operations allowed on it.
Show solution
class BankAccount:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("insufficient funds")
else:
self.balance -= amount
account = BankAccount()
for _ in range(int(input())):
action, amount = input().split()
getattr(account, action)(int(amount))
print(f"balance: {account.balance}")