Simple account program

Chris Rebert (cybercobra) cvrebert at gmail.com
Sat Mar 19 02:20:49 EST 2005


Since everyone's improving the program, I thought I'd just tweak Dennis
Lee Bieber's code a little. Here's the result. Good luck Ignorati!

import time

class Transaction(object):
    def __init__(self, payee, amount, date=None):
        # amount is the amt withdrawn/deposited
        self.payee = payee
        self.amount = amount
        if date is None:
            date = time.localtime()
        self.date = date

    def formatEntry(self):
        if self.amount > 0:
            transType = "DEPOSIT"
        elif self.amount < 0:
            transType = "WITHDRAWAL"
        return transType+"\t\t%s\t%s\t%s" % ((self.date[0],
                                              self.date[1],
                                              self.date[2]),
                                             self.amount,
                                             self.payee)

class Account(object):
    def __init__(self, acctName, initialBalance):
        self.acctName = accName
        self.transacts = [Transaction("Initial Balance",
initialBalance)]
        self.balance = initialBalance

    def deposit(self, payee, amt, date=None):
        assert amt >= 0, "amt must be positive for a deposit, got
"+str(amt)
        self.transacts.append(Transaction(payee, amt, date))
        self.balance += amt

    def withdraw(self, payee, amt, date=None):
        assert amt <= 0, "amt must be negative for a withdrawl, got
"+str(amt)
        self.transacts.append(Transaction(payee, amt, date))
        self.balance -= amt

    def printRegister(self):
        print "Transaction\tDate\t\tAmount\tPayee"
        for t in self.transacts:
            print t.formatEntry()

if __name__ == "__main__":
    myAccount = Account("Sample Account", 0.0)

    while True:
        print """
        Select transaction type:
            D)eposit
            W)ithdrawal
            P)rint register

            Q)uit
        """

        rep = raw_input("Enter your choice => ")
        rep = rep[0].upper()

        if rep == "D" or rep == "W":
            who = raw_input("Enter payee name => ")
            amt = float(raw_input("Enter transaction amount => "))
            if rep == "D":
                myAccount.deposit(who, amt)
            else:
                myAccount.withdraw(who, amt)

        elif rep == "P":
            print "\n"
            myAccount.printRegister()
            print "\n"

        elif rep == "Q":
            break

        else:
            print "Invalid Input, Please Try Again"
            print

        print "\tCurrent Balance: %s\n" % myAccount.balance




More information about the Python-list mailing list