Python Implementation of a Bank Account Class Supporting Deposit and Withdrawal
We will create a simple bank account class. This class will contain basic account information, such as account name and balance, and support deposit and withdrawal operations.
Example
class BankAccount:
def __init__(self, account_name, initial_balance=0):
self.account_name = account_name
self.balance = initial_balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited {amount}. New balance is {self.balance}.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > 0 and amount <= self.balance:
self.balance -= amount
print(f"Withdrew {amount}. New balance is {self.balance}.")
else:
print("Invalid withdrawal amount.")
def get_balance(self):
return self.balance
# Example usage
account = BankAccount("John Doe", 100)
account.deposit(50)
account.withdraw(20)
print(f"Final balance is {account.get_balance()}.")
def __init__(self, account_name, initial_balance=0):
self.account_name = account_name
self.balance = initial_balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited {amount}. New balance is {self.balance}.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > 0 and amount <= self.balance:
self.balance -= amount
print(f"Withdrew {amount}. New balance is {self.balance}.")
else:
print("Invalid withdrawal amount.")
def get_balance(self):
return self.balance
# Example usage
account = BankAccount("John Doe", 100)
account.deposit(50)
account.withdraw(20)
print(f"Final balance is {account.get_balance()}.")
Code Analysis:
__init__The method is the constructor of the class, used to initialize the account name and initial balance.depositThe method is used for deposits, increasing the account balance.withdrawThe method is used for withdrawals, decreasing the account balance, but ensuring no overdraft.get_balanceThe method returns the current account balance.
Output Result:
Deposited 50. New balance is 150. Withdrew 20. New balance is 130. Final balance is 130.Other Extensions
Python3 Examples