Join WhatsApp

Python banking system complete code

By admin

26/March/2026 , 8:58 AM

import sqlite3
from datetime import datetime

# ---------- DATABASE ----------
class Database:
    def __init__(self):
        self.conn = sqlite3.connect("bank.db")
        self.cur = self.conn.cursor()
        self.setup()

    def setup(self):
        self.cur.execute('''CREATE TABLE IF NOT EXISTS users(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE,
            password TEXT
        )''')

        self.cur.execute('''CREATE TABLE IF NOT EXISTS accounts(
            acc_no INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER,
            balance INTEGER DEFAULT 0
        )''')

        self.cur.execute('''CREATE TABLE IF NOT EXISTS transactions(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            acc_no INTEGER,
            type TEXT,
            amount INTEGER,
            time TEXT
        )''')

        self.conn.commit()


# ---------- ACCOUNT ----------
class Account:
    def __init__(self, db, acc_no):
        self.db = db
        self.acc_no = acc_no

    def deposit(self, amount):
        self.db.cur.execute("UPDATE accounts SET balance = balance + ? WHERE acc_no = ?", (amount, self.acc_no))
        self.db.cur.execute("INSERT INTO transactions(acc_no,type,amount,time) VALUES(?,?,?,?)",
                            (self.acc_no, "Deposit", amount, datetime.now()))
        self.db.conn.commit()
        print("✅ Deposited Successfully")

    def withdraw(self, amount):
        self.db.cur.execute("SELECT balance FROM accounts WHERE acc_no=?", (self.acc_no,))
        balance = self.db.cur.fetchone()[0]

        if amount <= balance:
            self.db.cur.execute("UPDATE accounts SET balance = balance - ? WHERE acc_no = ?", (amount, self.acc_no))
            self.db.cur.execute("INSERT INTO transactions(acc_no,type,amount,time) VALUES(?,?,?,?)",
                                (self.acc_no, "Withdraw", amount, datetime.now()))
            self.db.conn.commit()
            print("✅ Withdraw Successful")
        else:
            print("❌ Insufficient Balance")

    def check_balance(self):
        self.db.cur.execute("SELECT balance FROM accounts WHERE acc_no=?", (self.acc_no,))
        print("💰 Balance:", self.db.cur.fetchone()[0])

    def transactions(self):
        self.db.cur.execute("SELECT type, amount, time FROM transactions WHERE acc_no=?", (self.acc_no,))
        data = self.db.cur.fetchall()

        print("\n📜 Transaction History:")
        for t in data:
            print(f"{t[0]} | ₹{t[1]} | {t[2]}")


# ---------- BANK ----------
class Bank:
    def __init__(self):
        self.db = Database()

    def register(self):
        username = input("Enter Username: ")
        password = input("Enter Password: ")

        try:
            self.db.cur.execute("INSERT INTO users(username,password) VALUES(?,?)", (username, password))
            user_id = self.db.cur.lastrowid
            self.db.cur.execute("INSERT INTO accounts(user_id) VALUES(?)", (user_id,))
            self.db.conn.commit()
            print("✅ Account Created Successfully")
        except:
            print("❌ Username already exists")

    def login(self):
        username = input("Enter Username: ")
        password = input("Enter Password: ")

        self.db.cur.execute("SELECT id FROM users WHERE username=? AND password=?", (username, password))
        user = self.db.cur.fetchone()

        if user:
            self.db.cur.execute("SELECT acc_no FROM accounts WHERE user_id=?", (user[0],))
            acc_no = self.db.cur.fetchone()[0]
            print("✅ Login Successful")
            return Account(self.db, acc_no)
        else:
            print("❌ Invalid Credentials")
            return None


# ---------- MAIN ----------
def main():
    bank = Bank()

    while True:
        print("\n===== BANK SYSTEM =====")
        print("1. Register")
        print("2. Login")
        print("3. Exit")

        choice = input("Choose: ")

        if choice == '1':
            bank.register()

        elif choice == '2':
            account = bank.login()

            if account:
                while True:
                    print("\n--- MENU ---")
                    print("1. Deposit")
                    print("2. Withdraw")
                    print("3. Balance")
                    print("4. Transactions")
                    print("5. Logout")

                    ch = input("Choose: ")

                    if ch == '1':
                        amt = int(input("Enter Amount: "))
                        account.deposit(amt)

                    elif ch == '2':
                        amt = int(input("Enter Amount: "))
                        account.withdraw(amt)

                    elif ch == '3':
                        account.check_balance()

                    elif ch == '4':
                        account.transactions()

                    elif ch == '5':
                        break

        elif choice == '3':
            print("👋 Exiting...")
            break


if __name__ == "__main__":
    main()
#News #Coding #Learning

Leave a Comment