By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,907 Members | 1,963 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

Simple account program

P: n/a
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(self,
self.transaction =
import time
time.asctime()
raw_input("Is this a deposit or withdrawl?")
if withdrawl:
elif
raw_input("Please enter amount here.")

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

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

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

Jul 18 '05 #1
Share this Question
Share on Google+
17 Replies


P: n/a
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('deposit',amt)

def withdraw(self, amt):
self.balance = self.balance - amt
self.save('withdrawl', 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,self.balance)

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

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

Jul 18 '05 #2

P: n/a
Ron
Igorati wrote:
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.


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.name = name
transaction.amount = amount
transaction.type = ''
self.ledger.append(transaction)

def getbalance(self):
balance = 0.0
for transaction in self.ledger:
balance += transaction.amount
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.newtransaction( name, amount, type)

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

Jul 18 '05 #3

P: n/a
Ron
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.name = name
transaction.amount = amount
transaction.type = ''
self.ledger.append(transaction)

def getbalance(self):
balance = 0.0
for transaction in self.ledger:
balance += transaction.amount
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.newtransaction( name, amount, type)

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

Jul 18 '05 #4

P: n/a
Igorati wrote:
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(self,
self.transaction =
import time
time.asctime()
raw_input("Is this a deposit or withdrawl?")
if withdrawl:
elif
raw_input("Please enter amount here.")

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

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

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


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.TransActList 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

Jul 18 '05 #5

P: n/a
On 17 Mar 2005 13:12:34 -0800, "M.E.Farmer" <me*****@hotmail.com>
declaimed the following in comp.lang.python:

Stay away from inheritance till you have an understanding of namespace,
no need in getting mixed up.
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(self):
return "DEPOSIT \t%s\t%s\t%s" % ((self._Date[0],
self._Date[1],
self._Date[2]),
self._Amount,
self._Payee)

class Withdrawal(object):
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(self):
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._Transactions = []
if InitialBalance < 0:
self._Transactions.append(Withdrawal("Initial Balance",
InitialBalance))
else:
self._Transactions.append(Deposit("Initial Balance",
InitialBalance))
self._Balance = InitialBalance

def addDeposit(self, Payee, Amount, Date=None):
self._Transactions.append(Deposit(Payee, Amount, Date))
self._Balance += abs(Amount)

def addWithdrawal(self, Payee, Amount, Date=None):
self._Transactions.append(Withdrawal(Payee, Amount, Date))
self._Balance -= abs(Amount)

def getBalance(self):
return self._Balance

def printRegister(self):
print "Transaction\tDate\t\tAmount\tPayee"
for t in self._Transactions:
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.addDeposit(who, amt)
else:
myAccount.addWithdrawal(who, amt)

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

if rep == "Q":
break

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

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #6

P: n/a
wes weston schrieb:
Why have transactions not associated with accounts?
All transactions are related to an account; have
a self.TransActList 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?


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 programmatically is to have two
lists, accounts and transactions. Each transaction generates a new
entry in the list of transactions:

translist.append(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_account:
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 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
-------------------------------------------------------------------
Jul 18 '05 #7

P: n/a
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.

Jul 18 '05 #8

P: n/a
On Fri, 18 Mar 2005 14:54:57 +0100, Peter Maas <pe***@somewhere.com>
declaimed the following in comp.lang.python:

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.
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.
-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #9

P: n/a
Igorati wrote:
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.


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
http://docs.python.org/tut/node4.html
-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

Jul 18 '05 #10

P: n/a
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

Jul 18 '05 #11

P: n/a
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.

Jul 18 '05 #12

P: n/a
On Sun, 20 Mar 2005 10:20:02 -0500, "Igorati" <wa***********@yahoo.com>
declaimed the following in comp.lang.python:
I was looking at both the programs and I got Dennis Lee Bieber's code to
My code still needs the additions of that search feature you
mentioned, along with the data persistence (storing/retrieving the data
between uses).
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
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: class Account(object):
def __init__(self, acctName, initialBalance):
self.acctName = accName
self.transacts = [Transaction("Initial Balance",
initialBalance)]
self.balance = initialBalance
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:
def deposit(self, payee, amt, date=None):
assert amt >= 0, "amt must be positive for a deposit, got
"+str(amt)
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 "+...
-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #13

P: n/a
Question then, do I do an

import pickle

pickle.dump ((withdrawl), file ('account.pickle', 'w'))
pickle.dump ((deposit), file ('account.pickle', 'w'))
Am I on the right track?
Jul 18 '05 #14

P: n/a
Igorati wrote:
pickle.dump ((withdrawl), file ('account.pickle', 'w')) ^^^^^^^^^

Is this banking done with an American accent? :-)
pickle.dump ((deposit), file ('account.pickle', 'w'))
Am I on the right track?


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
http://www.cosc.canterbury.ac.nz/~greg
Jul 18 '05 #15

P: n/a
You probably want:

import pickle
pickle.dump(myAccount, file("account.pickle", "w"))

To reload your account:
import pickle
myAccount = pickle.load(file("account.pickle"))

Jul 18 '05 #16

P: n/a
ah thank you again. Anyone know of a good place to get information about TK
inter. I am gonna try and make this program somewhat of a GUI. Thank you
again.

Jul 18 '05 #17

P: n/a
Igorati wrote:
ah thank you again. Anyone know of a good place to get information about TK
inter. I am gonna try and make this program somewhat of a GUI. Thank you
again.

http://docs.python.org/lib/module-Tkinter.html
http://www.pythonware.com/library/tk...tion/index.htm
http://infohost.nmt.edu/tcc/help/pubs/tkinter/

Kent
Jul 18 '05 #18

This discussion thread is closed

Replies have been disabled for this discussion.