Bank Account

Source: Dec 2023, Task 7 (DTU 02002/02003). Study solution — not an official answer key.

Problem

Implement class BankAccount with attribute balance:

Example
>>> my_account = BankAccount(1000)
>>> my_account.deposit(500)
>>> my_account.withdraw(200)
200
>>> my_account.withdraw(2000)
0
>>> my_account.get_balance()
1300

Approach

Store self.balance. In withdraw, check amount <= self.balance before updating.

Solution

Show solution Hide solution
Solution
class BankAccount:
    def __init__(self, balance):
        self.balance = balance

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

    def withdraw(self, amount):
        if amount > self.balance:
            return 0
        self.balance -= amount
        return amount

    def get_balance(self):
        return self.balance