1.A bank account class
IntermediateWrite a BankAccount class with an owner and a balance (default 0). Add deposit(amount) and withdraw(amount) methods. Both must raise a ValueError for amounts that are not positive, and withdraw must also raise one if there is not enough money. Show a deposit, a withdrawal and a failed withdrawal.
Show hint
Store values on self in __init__. Raise errors with raise ValueError("message") before changing the balance.
Show solution
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError("Withdrawal must be positive")
if amount > self.balance:
raise ValueError("Insufficient funds")
self.balance -= amount
account = BankAccount("Asha")
account.deposit(1000)
account.withdraw(300)
print(account.owner, account.balance)
try:
account.withdraw(5000)
except ValueError as error:
print("Error:", error)
print(account.balance)Asha 700
Error: Insufficient funds
700