Python Program for a Bank Account Using a Class
Intermediate · Classes and objects
This program models a bank account as a class with methods to deposit money, withdraw it and print a statement. It refuses to withdraw more than the account holds, and keeps a list of every transaction for the mini statement.
Program
Cannot withdraw Rs. 5000: the balance is only Rs. 1200 Statement for Riya: - Deposited Rs. 500 - Withdrew Rs. 300 Balance: Rs. 1200
How it works
- Each account object keeps its own
owner,balanceandhistory, set up in__init__;balance=0lets you open an account with no starting amount. deposit()adds to the balance andwithdraw()takes money out, and both record what happened inhistory.withdraw()checks the balance first and refuses any amount larger than it, so the balance can never go below zero.statement()prints every transaction followed by the current balance, like a mini statement from an ATM.- Changing the balance only through methods, instead of writing
account.balance = ...directly, is called encapsulation: the class makes sure its rules are always followed.
Other ways to write it
Transferring money between two accounts
Riya sent Rs. 750 to Aman Aman cannot send Rs. 5000 Riya has Rs. 1250 and Aman has Rs. 1250
A method can take another object as an argument, so transfer() changes two accounts in one call.
Raising an error instead of printing
Withdrew Rs. 400 - balance now Rs. 600 Could not withdraw Rs. 900 - the balance is only Rs. 600
Raising an error lets the code that called withdraw() decide what to do about it, which is how real programs report problems, instead of the method printing a message itself.
Try it yourself
Add a minimum balance rule: refuse any withdrawal that would leave less than Rs. 500 in the account.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises