[Tutor] Consolidate reused code blocks
David
david at abbottdavid.com
Thu Apr 9 02:38:09 CEST 2009
Hi Everyone,
I have a simple todo list program with functions to add, delete, edit
and print out a list of todo's. I need to understand how to remove the
same blocks of code I use in each function. Should I create a class for
the same block of code I am including in each function? Here are two of
the functions;
def main():
print '\nYour current Todo list is: \n'
if os.path.exists('todo.dat'):
try:
fname = open('todo.dat', 'rb')
data = cPickle.Unpickler(fname)
todo = data.load()
load_todo(todo)
for k, v in todo.iteritems():
print k, v[0], v[1]
finally:
fname.close()
menu()
else:
todo = {}
print "You have 0 todo's"
menu()
def del_todo():
if os.path.exists('todo.dat'):
try:
fname = open('todo.dat', 'rb')
data = cPickle.Unpickler(fname)
todo = data.load()
load_todo(todo)
finally:
fname.close()
else:
todo = {}
try:
print '\nYour current Todo list is: \n'
for k, v in todo.iteritems():
print k
answer = raw_input('\nWhich Todo do you want to remove? ')
del todo[answer]
print '\nDeleted Todo', answer
print '\nYour current Todo list is: \n'
for k, v in todo.iteritems():
print k, v[0],v[1]
load_todo(todo)
except KeyError, e:
print '\nError! Please enter the Todo to be removed.\n'
print 'Case and spaces are important.'
Here is the whole thing :)
http://linuxcrazy.pastebin.com/f4206de5a
Thanks for your time,
-david
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
More information about the Tutor
mailing list