Create a program that simulates a simple banking system. This exercise will involve working with variables, functions, loops, and conditional statements to manage bank accounts and perform basic banking operations.
-
Define a class called BankAccount that represents a bank account. The class should have attributes such as the account holder's name, account number, and current balance.
-
Include error handling to handle withdrawing more money than the account balance allows, by implementing the InsufficientFundsError class.
-
Implement methods within the BankAccount class for depositing money, withdrawing money, checking the account balance... These methods should update the account balance accordingly.
-
Then implement a BankLedger class that keeps track of all the bank accounts. This class should have methods such as deposit, withdraw, and some utility methods for adding and removing accounts.
class InsufficientFundsError(Exception):
def __init__(self, message="Insufficient funds"):
self.message = message
super().__init__(self.message)
class BankAccount:
def __init__(self, name:str, number:int, balance:float):
self.account_holder_name:str = name
self.account_number:int = number
self.balance:float = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError("Insufficient funds, cannot withdraw {amount}, only {self.balance} available")
else:
self.balance -= amount
def deposit(self, amount):
self.balance += amount
# TODO: Add more methods, for example:
# transfer_money(from_account, to_account, amount)
# change_name(new_name)
import codewars_test as test
from solution import BankAccount, InsufficientFundsError
print(dir(test))
@test.describe("BankAccount")
def test_bank_account():
@test.it("should withdraw the correct amount when there are sufficient funds")
def test_withdraw_sufficient_funds():
account = BankAccount("John Doe", 123456789, 100.0)
account.withdraw(50.0)
test.assert_equals(account.balance, 50.0, "Balance should be 50.0")
@test.it("should raise InsufficientFundsError when there are insufficient funds")
def test_withdraw_insufficient_funds():
account = BankAccount("June Doe", 987654321, 100.0)
test.expect(InsufficientFundsError, account.withdraw, 200.0)
test.assert_equals(account.balance, 100.0, "Balance should remain unchanged when insufficient funds")
# TODO: Write more tests!