Simple account program

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Igorati

    #1

    Simple account program

    Hello all, I am still needing some help on this code, I have gone a bit
    further on it. Thank you for the help. I am trying to understand how to
    make the file searchable and how I am to make the deposit and withdrawl
    interact with the transaction class.
    I need to just search the file only for the deposits and withdrawls and
    the amount in the account with a time stamp. Thank you for your
    assistance.

    class Account:
    def __init__(self, initial):
    self.balance = initial
    def deposit(self, amt):
    self.balance = self.balance + amt
    def withdraw(self, amt):
    self.balance = self.balance - amt
    def getbalance(self ):
    return self.balance

    class Transactoin:
    def transaction(sel f,


    self.transactio n =
    import time
    time.asctime()
    raw_input("Is this a deposit or withdrawl?")
    if withdrawl:
    elif
    raw_input("Plea se enter amount here.")

    class Deposit(Transac tion):
    def deposit(self, amt):
    self.balance = self.balance + amt
    def getbalance(self ):
    return self.balance

    class Withdrawl(Trasa ction):
    def withdrawl(self, amt):
    self.balance = self.balance - amt
    def getbalance(self ):
    return self.balance
    import pickle
    pickle.dump ((withdrawl), file ('account.pickl e', 'w'))
    pickle.dump ((deposit), file ('account.pickl e', 'w'))



    print "Your current account total is.", self.balance

  • M.E.Farmer

    #2
    Re: Simple account program

    Igorati,
    I wished I could give you a simple fix, BUT...
    You need to really re-read the docs and do some tutors first .
    Your understanding of classes and namespaces is flawed and will not
    become clear without futher study.

    search strategy:
    python namespaces
    python class
    python tutor

    Classes are like containers.
    Classes have there own namespace, "self".
    Multiple classes do not share namespaces.
    Stay away from inheritance till you have an understanding of namespace,
    no need in getting mixed up.
    Withdrawl, Deposit, Transaction should be members of the account class.
    That way they can share a namespace and simplify your design.
    Why do you need to search a pickle?
    Pickle an instance of the class and unpickle it when needed and your
    data will be however it was in your instance.
    If you have real code post it because this code does not work and never
    will.
    Quit posting homework, you can ask for occasional help, but this is the
    third time i have seen this, it is getting worse and you have been
    warned before ;)
    Surely in the month since you first asked you could have read a bit of
    documentation.
    # this is not complete or even tested it is just an example ( based on
    your code )
    import time
    class Account:
    def __init__(self, initial):
    self.balance = initial
    self.history = {}

    def deposit(self, amt):
    self.balance = self.balance + amt
    self.save('depo sit',amt)

    def withdraw(self, amt):
    self.balance = self.balance - amt
    self.save('with drawl', amt)

    def getbalance(self ):
    return self.balance

    def gethistory(self ):
    return self.history

    def save(self,trans ,amount):
    # store the transaction type, amount, balance
    self.history[self.timestamp( )] = (trans,amount,s elf.balance)

    def timestamp(self) :
    return time.asctime()

    def transaction(sel f):
    withdrawl = raw_input("Is this a deposit or withdrawl?")
    amount = raw_input("Plea se enter amount here.")
    if withdrawl.lower () in ["withdrawl" ,"w"]:
    self.withdraw(a mount)
    else:
    self.deposit(am ount)
    hth,
    M.E.Farmer

    Comment

    • Ron

      #3
      Re: Simple account program

      Igorati wrote:
      [color=blue]
      > Hello all, I am still needing some help on this code, I have gone a bit
      > further on it. Thank you for the help. I am trying to understand how to
      > make the file searchable and how I am to make the deposit and withdrawl
      > interact with the transaction class.
      > I need to just search the file only for the deposits and withdrawls and
      > the amount in the account with a time stamp. Thank you for your
      > assistance.[/color]

      Hi Igorati,

      In a ledger program I wrote, I setup the account classes something like
      below. I'm not sure what you mean by searching a file. Are you trying
      to read an already existing file?

      class Transaction:
      def __init__(self):
      self.name = ''
      self.amount = 0.0
      self.type = ''

      class Account:
      def __init__(self, name=''):
      self.name = name
      self.ledger = []

      def newtransaction( self, name, amount, type):
      transaction = Transaction()
      transaction.nam e = name
      transaction.amo unt = amount
      transaction.typ e = ''
      self.ledger.app end(transaction )

      def getbalance(self ):
      balance = 0.0
      for transaction in self.ledger:
      balance += transaction.amo unt
      return balance

      # Within your main program somewhere.
      myaccount = Account( 'Savings Account')

      # get transaction data from user or file
      name = 'cash'
      amount = 20.0
      type = 'deposite'
      myaccount.newtr ansaction( name, amount, type)

      print "%s Balance is $ %.2f" % (myaccount.name , myaccount.getba lance())





      Comment

      • Ron

        #4
        Re: Simple account program

        The indentation got messed up a bit, it should look like this.

        class Transaction:
        def __init__(self):
        self.name = ''
        self.amount = 0.0
        self.type = ''

        class Account:
        def __init__(self, name=''):
        self.name = name
        self.ledger = []

        def newtransaction( self, name, amount, type):
        transaction = Transaction() # Create transaction instance.
        transaction.nam e = name
        transaction.amo unt = amount
        transaction.typ e = ''
        self.ledger.app end(transaction )

        def getbalance(self ):
        balance = 0.0
        for transaction in self.ledger:
        balance += transaction.amo unt
        return balance

        # Within your main program somewhere.

        # Create an instance of the account object.
        myaccount = Account( 'Savings Account')

        # get transaction data from user or file
        name = 'cash'
        amount = 20.0
        type = 'deposite'
        myaccount.newtr ansaction( name, amount, type)

        print "%s Balance is $ %.2f" % (myaccount.name , myaccount.getba lance())

        Comment

        • wes weston

          #5
          Re: Simple account program

          Igorati wrote:[color=blue]
          > Hello all, I am still needing some help on this code, I have gone a bit
          > further on it. Thank you for the help. I am trying to understand how to
          > make the file searchable and how I am to make the deposit and withdrawl
          > interact with the transaction class.
          > I need to just search the file only for the deposits and withdrawls and
          > the amount in the account with a time stamp. Thank you for your
          > assistance.
          >
          > class Account:
          > def __init__(self, initial):
          > self.balance = initial
          > def deposit(self, amt):
          > self.balance = self.balance + amt
          > def withdraw(self, amt):
          > self.balance = self.balance - amt
          > def getbalance(self ):
          > return self.balance
          >
          > class Transactoin:
          > def transaction(sel f,
          >
          >
          > self.transactio n =
          > import time
          > time.asctime()
          > raw_input("Is this a deposit or withdrawl?")
          > if withdrawl:
          > elif
          > raw_input("Plea se enter amount here.")
          >
          > class Deposit(Transac tion):
          > def deposit(self, amt):
          > self.balance = self.balance + amt
          > def getbalance(self ):
          > return self.balance
          >
          > class Withdrawl(Trasa ction):
          > def withdrawl(self, amt):
          > self.balance = self.balance - amt
          > def getbalance(self ):
          > return self.balance
          > import pickle
          > pickle.dump ((withdrawl), file ('account.pickl e', 'w'))
          > pickle.dump ((deposit), file ('account.pickl e', 'w'))
          >
          >
          >
          > print "Your current account total is.", self.balance
          >[/color]

          Igorati,
          Suggestion. Write out what you want to do in
          words such that all the things you want to do are
          there as unambiguously clear as you can get it.
          It will help your thinking on the problem, the
          design, and the code; and help anyone trying to
          help you.
          Why have transactions not associated with accounts?
          All transactions are related to an account; have
          a self.TransActLi st in Account.
          You have "amount" in both Withdrawl and Deposit
          both derived from Transaction. If Transactions always
          have an amount, why not put amount in the transactions
          class? But we don't know.
          wes

          Comment

          • Dennis Lee Bieber

            #6
            Re: Simple account program

            On 17 Mar 2005 13:12:34 -0800, "M.E.Farmer " <mefjr75@hotmai l.com>
            declaimed the following in comp.lang.pytho n:

            [color=blue]
            > Stay away from inheritance till you have an understanding of namespace,
            > no need in getting mixed up.[/color]

            You can blame me for that, I think... One of my attempts at
            helping -- oh, so many weeks ago -- had me mention that withdrawals and
            deposits are both transactions that only differ by the direction of
            money flow.



            The following are /general/ comments for the original querant...

            Do NOT attempt to maintain a running balance inside each
            transaction. A transaction consists of only three things: The date, the
            amount (with direction... a withdrawal of $40 could be stored as a
            transaction of $-40, while a deposit of $40 would be a transaction of
            $+40; subclasses would then be responsible for converting from the user
            view ($40) to the stored view ($-40/$+40) and back), and the purpose (or
            name of person getting/giving the money).

            The account then maintains the running balance, along with a
            LIST of transactions. You need the list in order to recreate the
            transactions for searching purposes; it is that list which has to be
            pickled/unpickled (or otherwise saved/restored). If you define a
            comparison operator for transactions, you could even run a sort
            operation on the list to ensure that transactions are in date order.

            And lastly, something I shouldn't be doing -- though since there
            is no search, no formatted date handling, no persistance file, and only
            two comments... there is still quite a bit to be implemented...

            -=-=-=-=-=-=-=-=-=-=-=-=-
            import time

            class Deposit(object) :
            def __init__(self, Payee, Amount, Date=None):
            # deposits are always positive values
            self._Payee = Payee
            self._Amount = abs(Amount)
            if Date is None:
            Date = time.localtime( )
            self._Date = Date

            def formatEntry(sel f):
            return "DEPOSIT \t%s\t%s\t%s" % ((self._Date[0],
            self._Date[1],
            self._Date[2]),
            self._Amount,
            self._Payee)

            class Withdrawal(obje ct):
            def __init__(self, Payee, Amount, Date=None):
            # withdrawals are always negative
            self._Payee = Payee
            self._Amount = -abs(Amount)
            if Date is None:
            Date = time.localtime( )
            self._Date = Date

            def formatEntry(sel f):
            return "WITHDRAWAL\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, AccName, InitialBalance) :
            self._AccName = AccName
            self._Transacti ons = []
            if InitialBalance < 0:
            self._Transacti ons.append(With drawal("Initial Balance",
            InitialBalance) )
            else:
            self._Transacti ons.append(Depo sit("Initial Balance",
            InitialBalance) )
            self._Balance = InitialBalance

            def addDeposit(self , Payee, Amount, Date=None):
            self._Transacti ons.append(Depo sit(Payee, Amount, Date))
            self._Balance += abs(Amount)

            def addWithdrawal(s elf, Payee, Amount, Date=None):
            self._Transacti ons.append(With drawal(Payee, Amount, Date))
            self._Balance -= abs(Amount)

            def getBalance(self ):
            return self._Balance

            def printRegister(s elf):
            print "Transaction\tD ate\t\tAmount\t Payee"
            for t in self._Transacti ons:
            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("Ente r your choice => ")
            rep = rep[0].upper()

            if rep == "D" or rep == "W":
            who = raw_input("Ente r payee name => ")
            amt = float(raw_input ("Enter transaction amount => "))
            if rep == "D":
            myAccount.addDe posit(who, amt)
            else:
            myAccount.addWi thdrawal(who, amt)

            if rep == "P":
            print "\n"
            myAccount.print Register()
            print "\n"

            if rep == "Q":
            break

            print "\tCurrent Balance: %s\n" % myAccount.getBa lance()

            --[color=blue]
            > =============== =============== =============== =============== == <
            > wlfraed@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
            > wulfraed@dm.net | Bestiaria Support Staff <
            > =============== =============== =============== =============== == <
            > Home Page: <http://www.dm.net/~wulfraed/> <
            > Overflow Page: <http://wlfraed.home.ne tcom.com/> <[/color]

            Comment

            • Peter Maas

              #7
              Re: Simple account program

              wes weston schrieb:[color=blue]
              > Why have transactions not associated with accounts?
              > All transactions are related to an account; have
              > a self.TransActLi st in Account.[/color]
              [color=blue]
              > You have "amount" in both Withdrawl and Deposit
              > both derived from Transaction. If Transactions always
              > have an amount, why not put amount in the transactions
              > class?[/color]

              That's a good idea. I don't know if Igorati is just doing an
              exercise or has the ambition to create a usable application.
              In the latter case it would be a good idea to learn the basics
              of double accounting (DA). In DA each transaction is associated
              with 2 accounts.

              DA tries to avoid signed numbers, but uses the terms debit and
              credit instead. debit and credit aren't simply synonyms for minus
              and plus because there are two types of accounts: assets and
              liabilities. Liabilities have a minus sign built in.

              For me this is crazy and I used to confuse things until I found
              three rules to memorize this:

              1. Positive flow of money is always recorded on the debit side.
              2. Assets account balances are computed without sign change.
              3. Liability account balances are computed with sign change.

              In matrix form:

              debit credit
              assets accont + -
              liabil account - +

              Example: You empty your piggybank to pay your debts:

              Amount is recorded on the debit side of debts and on the credit
              side of piggybank (rule 1). Both balances are lower, because credit
              is negative for assets (rule 2) and debit is negative for liabilities
              (rule 3).

              So the easiest way to handle this programmaticall y is to have two
              lists, accounts and transactions. Each transaction generates a new
              entry in the list of transactions:

              translist.appen d(trans(credit_ account, debit_account, amount))

              where amount is always positive. The account class has a balance
              method:

              class account:
              def balance(self, translist):
              bal = 0
              for e in translist:
              if self == e.debit_account :
              bal += e.amount
              if self == e.credit_accoun t:
              bal -= e.amount

              if self.acctype == "liability" :
              bal = -bal

              return bal

              --
              -------------------------------------------------------------------
              Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0
              E-mail 'cGV0ZXIubWFhc0 BtcGx1c3IuZGU=\ n'.decode('base 64')
              -------------------------------------------------------------------

              Comment

              • Igorati

                #8
                Re: Simple account program

                Thank you all for your help. I am sorry that I am struggling with
                programming. I still am attempting to "get it". Yes, I do need to stop
                posting homework assignments, perhaps I will learn to write code through
                more studying. I have gone through some toutorials if that makes you feel
                any better. I do have a desire to learn. Thank you again. I will go back
                and attempt to impliment this.

                Comment

                • Dennis Lee Bieber

                  #9
                  Re: Simple account program

                  On Fri, 18 Mar 2005 14:54:57 +0100, Peter Maas <peter@somewher e.com>
                  declaimed the following in comp.lang.pytho n:
                  [color=blue]
                  >
                  > That's a good idea. I don't know if Igorati is just doing an
                  > exercise or has the ambition to create a usable application.
                  > In the latter case it would be a good idea to learn the basics
                  > of double accounting (DA). In DA each transaction is associated
                  > with 2 accounts.
                  >[/color]
                  I don't think the "assignment " is for a full double-entry
                  accounting package. The original description, many moons back, sounded a
                  lot more like a computerized check-book register for use with a
                  petty-cash account.


                  --[color=blue]
                  > =============== =============== =============== =============== == <
                  > wlfraed@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
                  > wulfraed@dm.net | Bestiaria Support Staff <
                  > =============== =============== =============== =============== == <
                  > Home Page: <http://www.dm.net/~wulfraed/> <
                  > Overflow Page: <http://wlfraed.home.ne tcom.com/> <[/color]

                  Comment

                  • M.E.Farmer

                    #10
                    Re: Simple account program

                    Igorati wrote:[color=blue]
                    > Thank you all for your help. I am sorry that I am struggling with
                    > programming. I still am attempting to "get it". Yes, I do need to[/color]
                    stop[color=blue]
                    > posting homework assignments, perhaps I will learn to write code[/color]
                    through[color=blue]
                    > more studying. I have gone through some toutorials if that makes you[/color]
                    feel[color=blue]
                    > any better. I do have a desire to learn. Thank you again. I will go[/color]
                    back[color=blue]
                    > and attempt to impliment this.[/color]

                    Igorati,
                    A desire to learn , persistant study, and excercise is all you really
                    need ;)
                    I don't know how much you 'get' yet so I will assume you are just
                    starting.
                    We all have problems gaining that 'flash of insight' sometimes that
                    makes it all clear ( I am still trying to fully grasp metaclasses and
                    secretly envy Alex Martelli and just about every other genius on this
                    list ;).
                    So the best way I can tell you to learn a language is to read and write
                    it.
                    -Open a Python interpreter and start keying in Python and see what
                    happens.
                    -If you don't know what an interpreter is read the tutor

                    -Use dir() to see what an object exposes to you.
                    -Learn about list, dictionary, tuple and string methods it will save
                    you months.
                    -Buy a book on Python. I found it easier to grasp from a book than the
                    net, and now I have reference I can give to friends to get them
                    started.
                    -Read thru the standard library when you have the basics down the
                    insight you will gain is priceless.
                    -Pick a module and learn it. write a program that uses that module in
                    some way( this will make it easier to spot the time you actually need
                    to write a solution)
                    -Find a program you like and start adding 'features' to it or taking
                    out 'features' you don't like.
                    -Python tutor list may be more appropriate for you right now till you
                    are up and running. http://www.python.org/mailman/listinfo/tutor
                    -Just keep reading and writing Python , you will 'get it'.
                    hth,
                    M.E.Farmer

                    Comment

                    • Chris Rebert (cybercobra)

                      #11
                      Re: Simple account program

                      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(obj ect):
                      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(sel f):
                      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("In itial 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(Transact ion(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(Transact ion(payee, amt, date))
                      self.balance -= amt

                      def printRegister(s elf):
                      print "Transaction\tD ate\t\tAmount\t Payee"
                      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("Ente r your choice => ")
                      rep = rep[0].upper()

                      if rep == "D" or rep == "W":
                      who = raw_input("Ente r payee name => ")
                      amt = float(raw_input ("Enter transaction amount => "))
                      if rep == "D":
                      myAccount.depos it(who, amt)
                      else:
                      myAccount.withd raw(who, amt)

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

                      elif rep == "Q":
                      break

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

                      print "\tCurrent Balance: %s\n" % myAccount.balan ce

                      Comment

                      • Igorati

                        #12
                        Re: Simple account program

                        I was looking at both the programs and I got Dennis Lee Bieber's code to
                        work, then I tried the imporvements from Chris Reberts code but was unable
                        to get it to run. It said EOL error. I took out got and tried to move it
                        around but it didn't take. I took the else code at the end so that other
                        keys cannot be entered. I also see at the begining you are defining what a
                        deposit and withdrawl is. Ironically our next assignment is to make this
                        program handle errors and try to implement a GUI. I'm going to use the GUI
                        feauture and see what I come up with. Thank you all for your help. I know I
                        will be coding proper some day in the future.

                        Comment

                        • Dennis Lee Bieber

                          #13
                          Re: Simple account program

                          On Sun, 20 Mar 2005 10:20:02 -0500, "Igorati" <wade_stoddard@ yahoo.com>
                          declaimed the following in comp.lang.pytho n:
                          [color=blue]
                          > I was looking at both the programs and I got Dennis Lee Bieber's code to[/color]

                          My code still needs the additions of that search feature you
                          mentioned, along with the data persistence (storing/retrieving the data
                          between uses).
                          [color=blue]
                          > work, then I tried the imporvements from Chris Reberts code but was unable
                          > to get it to run. It said EOL error. I took out got and tried to move it[/color]

                          Did you account for how the file was wrapped by the news reader?
                          Pretty much anywhere you see a line start with an indent, and the next
                          line is against the left edge, is supposed to be one line.

                          For example:[color=blue]
                          > class Account(object) :
                          > def __init__(self, acctName, initialBalance) :
                          > self.acctName = accName
                          > self.transacts = [Transaction("In itial Balance",
                          > initialBalance)]
                          > self.balance = initialBalance[/color]

                          That "initialBalance )]" should be on the end of the line above
                          it (though in this case it is not a fatal error -- Python is smart
                          enough to see an unclosed ( and automatically assume it continues on the
                          next line.

                          But this one:
                          [color=blue]
                          > def deposit(self, payee, amt, date=None):
                          > assert amt >= 0, "amt must be positive for a deposit, got
                          > "+str(amt)[/color]

                          will fail, because literal strings cannot bridge multiple lines
                          (triple-quoted strings can, but that's for the future). The "+str(amt)
                          needs to be on the previous line (and since the " was wrapped, not got",
                          there must have been a space... deposit, got "+...


                          --[color=blue]
                          > =============== =============== =============== =============== == <
                          > wlfraed@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
                          > wulfraed@dm.net | Bestiaria Support Staff <
                          > =============== =============== =============== =============== == <
                          > Home Page: <http://www.dm.net/~wulfraed/> <
                          > Overflow Page: <http://wlfraed.home.ne tcom.com/> <[/color]

                          Comment

                          • Igorati

                            #14
                            Re: Simple account program

                            Question then, do I do an

                            import pickle

                            pickle.dump ((withdrawl), file ('account.pickl e', 'w'))
                            pickle.dump ((deposit), file ('account.pickl e', 'w'))
                            Am I on the right track?


                            Comment

                            • Greg Ewing

                              #15
                              Re: Simple account program

                              Igorati wrote:[color=blue]
                              > pickle.dump ((withdrawl), file ('account.pickl e', 'w'))[/color]
                              ^^^^^^^^^

                              Is this banking done with an American accent? :-)
                              [color=blue]
                              > pickle.dump ((deposit), file ('account.pickl e', 'w'))
                              > Am I on the right track?[/color]

                              The file you create in the second statement is going
                              to overwrite the first one. If you want to append
                              data to an existing file, you need to open it in
                              'a' mode.

                              --
                              Greg Ewing, Computer Science Dept,
                              University of Canterbury,
                              Christchurch, New Zealand

                              Comment

                              Working...