Simple Bank Account Management

Define a class BankAccount with a private variable balance. Implement methods for depositing and withdrawing money, ensuring that the balance cannot go negative.

Example 1:

account = BankAccount(100)
account.deposit(50)
account.withdraw(120)
print(account.get_balance())

Output: 30

Example 2:

account = BankAccount(200)
account.withdraw(250)
print(account.get_balance()) 

Output: 200

Ensure that the withdrawal method checks whether the amount to be withdrawn is less than or equal to the balance.

class BankAccount:
    def __init__(self, balance):
        self._balance = balance

    def deposit(self, amount):
        self._balance += amount

    def withdraw(self, amount):
        if amount <= self._balance:
            self._balance -= amount

    def get_balance(self):
        return self._balance

# Test the class
account = BankAccount(100)
account.deposit(50)
account.withdraw(120)
print(account.get_balance()) # Output: 30

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!