Python Practice › OOP Programs › Program 30
BankAccount class
Create a BankAccount class with account_number and balance, and methods to deposit and withdraw.
Output
AC-1001 1200 Error: insufficient funds
Approach
- Validate amounts in each method.
Solution
class BankAccount: def __init__(self, account_number, balance=0): self.account_number = account_number 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 > self.balance: raise ValueError("insufficient funds") self.balance -= amount acc = BankAccount("AC-1001", 1000)acc.deposit(500)acc.withdraw(300)print(acc.account_number, acc.balance)try: acc.withdraw(5000)except ValueError as e: print("Error:", e)Output
AC-1001 1200 Error: insufficient funds
Learn the concept
New to this topic? Read the lesson, then come back.