You are not logged in.

#1 2008-10-06 22:45:40

axion419
Member
Registered: 2007-04-12
Posts: 185

[Python] Created Simple Addressbook - How can I improve/clean my code?

I have nothing I need to program, So i am just trying to program for the sake of learning python.  Is there anyway to more efficiently do what I want ( append new address info to file or search for the criteria and print out line containing it)   Also, is there a more 'python' way of coding?  This code works, you can store and search, it also exits.  I know I need to error trap the hell out of it.  It would be nice to eventually make firstname always have the first letter capital, the rest lower, same with last name, for phone make sure its 10 digits and add the "-" if it isn there already etc.  I could use help with that.  ANy tips etc would be great.


# addressbook.py
# SIMPLE ADDRESS BOOK 
# data stored in addressbookdata
# Justin Seiser 10/5/08 

#Creating a Searching?

answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")

# IF we are creating 

if answer == "1" : 
    #print ("This is where we create")
    # collect information

    lastname = raw_input("What is the persons last name? ")
    firstname = raw_input("What is the persons first name? ")
    phone = raw_input("What id the persons phone number? ")
    email = raw_input("What is the persons email address? ")
    address = raw_input("What is the persons address? ")

    #create or append addressbookdata

    temp1 = open("addressbookdata","a")
    
    #create string to print to file
    #print temp1
    #print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address) 

    temp1.write(firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
    temp1.write("\n")

# SEARCHING FOR A RECORD

elif answer == "2" :
    print ("this is where we search")
    searchcriteria = raw_input("Enter your search Criteria, name? phone number etc ")
    print searchcriteria
    temp1 = open("addressbookdata","r")
    for line in temp1:
        if searchcriteria in line:
        print line


# USER DID NOT PICK CREATE OR SEARCH 

else :
    print ("Incorrect Answer")
    exit()

Last edited by axion419 (2008-10-06 22:49:51)

Offline

#2 2008-10-06 23:32:16

Righard
Member
From: Netherlands
Registered: 2007-12-13
Posts: 29

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

A good thing to start practising is using functions;
instead of using one long spagetti function devide it a little:

def search_database ():
    #search algoritm
def append_to_database (info):
    # append the info list to file
    # ofcourse this is a trival example but for the
    # learning experience maybe us a pickle:
    # http://www.python.org/doc/2.5.2/lib/module-pickle.html
def collect ():
    # collect information...
    append_to_file ([lastname, firstname]) # etc...
def menu ():
    # ask user what to do
    if answer == 1:
        collect ()
    if answer == 2:
        search_database()
    else:
        print str(answer) + "is not a valid option, try again"
        menu()

# start everthing:
menu ()

Offline

#3 2008-10-07 00:16:56

axion419
Member
Registered: 2007-04-12
Posts: 185

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

thank you, I will create function after class tonight, or after work tomorrow.  What is the rule when it comes to functions?  Use them everywhere you can?  I imagine so, that way you dont have duplicate code in the project?

Offline

#4 2008-10-07 00:46:26

Xyne
Administrator/PM
Registered: 2008-08-03
Posts: 6,963
Website

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

I think that's the general rule of thumb, yeah. Avoiding duplication not only means cleaner code, it also means that when you need to change the way that something is done, you only have to change it in one place. I wouldn't worry about "rules" too much... in just a few weeks you'll be looking at your old code mumbling to yourself "why did I do it that way?". You'll develop a feel for how to improve the overall structure of code as you go.

Btw, for capitalizing your strings, take a look at the string methods: http://www.python.org/doc/2.5.2/lib/string-methods.html
For more advanced formatting, I would suggest taking that as an opportunity to learn regular expressions (if you haven't done that already).

Also, if you're doing this mostly for the sake of learning, maybe take a look at creating a database instead of a flat file for your data. You could then try implementing more advanced queries (e.g. last name: Smith, first initial: J). I haven't done anything with databases in Python, but maybe sqlite3 would be a good place to start (it's built-in).

Your program would work well with a GUI too, so you could use it as a starting point to learning tkinter in python (also built-in).


My Arch Linux StuffForum EtiquetteCommunity Ethos - Arch is not for everyone

Offline

#5 2008-10-07 02:50:35

peets
Member
From: Montreal
Registered: 2007-01-11
Posts: 936
Website

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

I would split the program in two: one for entering addresses, and one for querying the addressbook. Furthermore, I would avoid interactivity by getting the info from command line arguments instead of a list of questions. That way the tool can be used in "batch mode" or in scripts. Plus it's easy to get the same functionality by writing a simple wrapper script.

Offline

#6 2008-10-12 19:00:29

axion419
Member
Registered: 2007-04-12
Posts: 185

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

I am going to make the program use functions, then split up and have it use command line arguments.  I almost have the function part finished, I just have an error that occurs if you search by a string that is not present in the address book.

# addressbook.py
# SIMPLE ADDRESS BOOK 
# data stored in addressbookdata
# Justin Seiser 10/5/08 


def search_database ():
    #search algoritm
    searchcriteria = raw_input("What do you want to search by? ")
    temp1 = open("addressbookdata","r")
    for line in temp1:
        if searchcriteria in line:
        print ("\n")
        print line
        print ("\n")
        else:
        print "Search yeilded zero results"
def append_to_database (info):
    # append the info list to file
    temp1 = open("addressbookdata","a")
    temp1.write(info)
    temp1.write("\n")
    print ("The record was added to the database address book ")

def collect ():
    # collect information...
    # append_to_file ([lastname, firstname]) # etc...
    lastname = raw_input("What is the persons last name? ")
    firstname = raw_input("What is the persons first name? ")
    phone = raw_input("What id the persons phone number? ")
    email = raw_input("What is the persons email address? ")
    address = raw_input("What is the persons address? ")
    info = (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
    append_to_database (info)
    
def menu ():
    answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")

    # ask user what to do
    if answer == "1":
        collect ()
    if answer == "2":
        search_database()
    else:
        print str(answer) + " is not a valid option, try again"
        menu()

# start everthing:
menu ()

Here is what happens when you run the code, select '2' to search the addres book, and then  enter "john" which is not in the address book.

Traceback (most recent call last):
  File "/home/justin/builds/address2.py", line 49, in <module>
    menu ()
  File "/home/justin/builds/address2.py", line 43, in menu
    search_database()
  File "/home/justin/builds/address2.py", line 10, in search_database
    temp1 = open("addressbookdata","r")
IOError: [Errno 2] No such file or directory: 'addressbookdata'
[justin@beast ~]$

THanks for any help.

Offline

#7 2008-10-12 19:28:17

pointone
Wiki Admin
From: Waterloo, ON
Registered: 2008-02-21
Posts: 379

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

The error is simply that no file "addressbookdata" exists in your working directory. You'll need to create the file before opening it for reading.

Next, I would suggest you remember to .close() all your files when done with them. This is most important when writing to files since the actual "physical" writes are cached until calling .close() or .flush(), but it is considered good coding practice to .close() after reading, as well.

# .close() example
f = open(filename, "r")
f.readlines()
f.close()
f = open(filename, "w")
f.write(data)
f.close()

Finally, I don't know what you're doing here:

        print ("\n")
        print line
        print ("\n")

...why the parenthesis? If you're thinking ahead to Python 3k, note that the "print as a function" feature is not yet implemented in Python 2.x.

Also, why not simply:

print "\n", line, "\n"
# Or better yet...
print "\n%s\n" % line

I recommend you read up on string formatting <http://diveintopython.org/getting_to_kn … rings.html>.

# Not so nice:
"text" + var1 + "text" + var2
# Much better:
"text %(var1)s text %(var2)s" % vars

M*cr*s*ft: Who needs quality when you have marketing?

Offline

#8 2008-10-12 19:36:28

Mashi
Member
Registered: 2007-02-19
Posts: 38

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

It might be interesting to have an address object that defines the __repr__ method, so you can store re-usable objects in your text file. For convenience you can extend this object off the builtin dictionary. It only takes a few lines of code and might make your addresses a little more manageable, because you would be able to define methods to do various different things.

I don't know if this is something you will really want to do, but since you said you are learning python i thought you might find it interesting:

Eg:

class address(dict):
    def __repr__(self):
        return 'address(' + dict.__repr__(self) + ')'

a = address()
a['line1'] = 'house'
a['line2'] = 'street'
a['zip'] = 'fds'

print "%s is a %s" % (str(a),type(a))
a = repr(a)
print "%s is a %s" % (str(a),type(a))
a = eval(a)
print "%s is a %s" % (str(a),type(a))

So now you can store the output of your address objects, one per line, and when you want to iterate through your addresses you can do this:

for line in open(addressfile,'r'):
    a = eval(line)
    # etc

Last edited by Mashi (2008-10-12 19:45:29)

Offline

#9 2008-10-12 19:45:56

pointone
Wiki Admin
From: Waterloo, ON
Registered: 2008-02-21
Posts: 379

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

Mashi wrote:

So now you can store the output of your address objects, one per line, and when you want to iterate through your addresses you can do this:

for line in open(addressfile,'r'):
    address = eval(line)
    # etc

That's a little scary... Good luck making sure no one tampers with your address file!

I think you have the right idea about storing the data in a dictionary-like object, but as far as writing to disk, I would recommend pickle/cpickle for that.

http://www.python.org/doc/2.5.2/lib/module-pickle.html


M*cr*s*ft: Who needs quality when you have marketing?

Offline

#10 2008-10-12 20:50:15

Dusty
Schwag Merchant
From: Medicine Hat, Alberta, Canada
Registered: 2004-01-18
Posts: 5,986
Website

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

pointone wrote:

I think you have the right idea about storing the data in a dictionary-like object, but as far as writing to disk, I would recommend pickle/cpickle for that.

http://www.python.org/doc/2.5.2/lib/module-pickle.html

Or sqlite.

http://www.python.org/doc/2.5.2/lib/module-sqlite3.html

Dusty

Offline

#11 2008-10-13 19:27:38

axion419
Member
Registered: 2007-04-12
Posts: 185

Re: [Python] Created Simple Addressbook - How can I improve/clean my code?

pointone, I cant beleive I missed that, I normally cd into my builds directory to run it, this time I ran it as python /path/tpbuilds.addressbook.py so that ISNT in my working directory.  So thanks for clearing that part up.  I dont know why I constructed the new line that way, lack of understanding I guess.  I can correct that one easy enough.  I also read that I needed to close the file, I just forgot.  I want to mess with this language enough to get the basic syntax down and then get a book to really learn it.  I can program in SQL and VBA so its just a matter of learning the language, programming is programming.  Thanks for everyones help, I think once I get these functions correct and working, I am going to learn to use sqlite since I already know SQL.  Learning  python and databases cant be anything but good.

Last edited by axion419 (2008-10-14 21:39:12)

Offline

Board footer

Powered by FluxBB