Sign in to follow this  
biggjoee5790

Simple Python Program help

Recommended Posts

biggjoee5790    229
Hi Guys, I created this simple contact book type program to simply store names and numbers. Its simply console based but I plan to add to it as I learn more. I have a few questions... The first one is Id like to know how to display the contents of the address book without it printing in the dictionary format. For example when I display all the contacts that have been added.. it shows them like this: {'Jim' : '17873382234, 'Bob : '1234332312'} ... Im trying to have it display in a more appealing way such as this: Bob --- 1277382881 Jim --- 1233314433 Mom --- 3243242234 I just want to get rid of the brackets and colons so it looks better. My next question is how can I make the program so it allows me to store more than 1 number for a certain contact? Such as Cell, home, work, etc. As far as i know, dictionaries only hold pairs (a term and a definition) I know i can simply just add another contact named "dad cell" or something like that, but it would be nice to have the added functionality. Heres the code for the program.. I know its messy because i didnt use any functions, Im gonna rewrite it in a bit and create functions for each choice such as newaddress(), editaddress(), etc.. this will clean it up a lot and make it more manageable. EDIT: This is the new code with functions added
def add_contact():
    """ adds a new contact """
    name = raw_input("\nWhat contact would you like to add? ")
    if name in contacts:
        print "\nSorry, that contact is already added."
    else:
        number = (raw_input("\nEnter this persons number: "))
        contacts[name] = number
        print "\nThe new contact has been added!"

def edit_contact():
    """ edits an existing contact """
    name = raw_input("\nWhat contact would you like to edit? ")
    if name in contacts:
        number = (raw_input("\nWhat is the new number? "))
        contacts[name] = number
        print "\nThe contact you chose has been edited!"
    else:
        print "\nThat contact doesnt exist!"

def del_contact(): 
    """ deletes an existing contact """
    name = raw_input("\nWhich contact would you like to delete? ")
    if name in contacts:
        del contacts[name]
        print "\nThe contact has been deleted!"
    else:
        print "\nThat contact doesnt exist!"

def view_all():
    """ displays all contacts """
    print     contacts
    raw_input("\nPress Enter to Continue")

def search_contact():
    """ searches for a contact """
    name = raw_input("\nWhose number do you want to search for? ")
    if name in contacts:
        print "\nThe number you have stored for", name, "is", contacts[name]
    else:
        print "\nThat contact doesnt exist!"


choice = None
contacts = {}

    
# Program Loop
while choice != 0:
    print "\nMain Menu"
    print "---------"
    print """
0 - Exit Program
1 - Add a Contact
2 - Edit a Contact
3 - Delete a Contact
4 - View All Contacts
5 - Search for a Contact
                    """

    choice = raw_input("\nWhat Would You Like To Do? ")

    if choice == "1":
        add_contact()

    elif choice == "2":
        edit_contact()

    elif choice == "3":
        del_contact()

    elif choice == "4":
        view_all()

    elif choice == "5":
        search_contact()

    elif choice == "0":
        print "\nGoodbye :)"
        break
        
    else:
        print "\nSorry, thats not a valid choice."


raw_input("\nPress Enter To Quit")
        

    


[Edited by - biggjoee5790 on March 1, 2008 2:07:57 PM]

Share this post


Link to post
Share on other sites
Oluseyi    2103
Quote:
Original post by biggjoee5790
The first one is Id like to know how to display the contents of the address book without it printing in the dictionary format.

Don't print the dictionary. Iterate over the items in it and print them out individually, formatting the key and value pairs as you please:
for contact in contacts.iteritems():
print "%s\t---%s" % contact


Quote:
My next question is how can I make the program so it allows me to store more than 1 number for a certain contact?

If you want to have a label for each of the numbers, then you essentially have a dictionary, right? So instead of a dictionary of names to numbers, you now have a dictionary of names to a dictionary of labels to numbers:
contacts = {"Bob" : {"cell" : 1234567890, "office" : 3216549870}, "Alice" : {...}, ...}


Eventually, you'll want a more sophisticated data structure than a simple dictionary for your database... or you'll want to store a complex structure as the value, while using an index as the key.

Share this post


Link to post
Share on other sites
biggjoee5790    229
Ok that makes alot of sense to iterate over them.. i shouldve thought of that :)

heres a new code i just wrote, its simply the same program done with functions... to me its much less sloppy:


def add_contact():
""" adds a new contact """
name = raw_input("\nWhat contact would you like to add? ")
if name in contacts:
print "\nSorry, that contact is already added."
else:
number = (raw_input("\nEnter this persons number: "))
contacts[name] = number
print "\nThe new contact has been added!"

def edit_contact():
""" edits an existing contact """
name = raw_input("\nWhat contact would you like to edit? ")
if name in contacts:
number = (raw_input("\nWhat is the new number? "))
contacts[name] = number
print "\nThe contact you chose has been edited!"
else:
print "\nThat contact doesnt exist!"

def del_contact():
""" deletes an existing contact """
name = raw_input("\nWhich contact would you like to delete? ")
if name in contacts:
del contacts[name]
print "\nThe contact has been deleted!"
else:
print "\nThat contact doesnt exist!"

def view_all():
""" displays all contacts """
print contacts
raw_input("\nPress Enter to Continue")

def search_contact():
""" searches for a contact """
name = raw_input("\nWhose number do you want to search for? ")
if name in contacts:
print "\nThe number you have stored for", name, "is", contacts[name]
else:
print "\nThat contact doesnt exist!"


choice = None
contacts = {}


# Program Loop
while choice != 0:
print "\nMain Menu"
print "---------"
print """
0 - Exit Program
1 - Add a Contact
2 - Edit a Contact
3 - Delete a Contact
4 - View All Contacts
5 - Search for a Contact
"""

choice = raw_input("\nWhat Would You Like To Do? ")

if choice == "1":
add_contact()

elif choice == "2":
edit_contact()

elif choice == "3":
del_contact()

elif choice == "4":
view_all()

elif choice == "5":
search_contact()

elif choice == "0":
print "\nGoodbye :)"
break

else:
print "\nSorry, thats not a valid choice."


raw_input("\nPress Enter To Quit")



Does anyone have any other advice for me on how to make this better?? Please critique me so i can improve.. remember though im just beginning :)

and thanks Oluseyi for the help




Share this post


Link to post
Share on other sites
realcore    134
A few notes on style first:
Your docstrings add very little at the moment. IE: add_contact(), "Adds a contact."
Using newlines the way you do. I feel they clutter up the string.
Adding _contact to all your function names. Unnecessary as I see it.
Of course, these are personal preferences.

On the actual code:
You should pass the contacts-dict as a parameter to your functions. Ex:
def add( contacts ):
contacts[name] = raw_input("Number? ")

This way you could have a personal contactlist, a work one and so on.

I like this:
for k, v in contacts:
print k, ":", v

You can refer to keys and values separately. (2.5 only..)

Another thing which is more "pythonic":
options = { "0":add_contacts, "1": ... }
while ...
opt = raw_input("Choice? ")
try:
options[opt]()
except KeyError:
print "Bad input."


Last thing I can think of is the way you break out of the loop to quit. A nicer method:
import sys
sys.exit()

This throws an exception which doesn't print any traceback. You can use this anywhere in your code, unlike your currant method.

Hope these little tips helps you out.

Share this post


Link to post
Share on other sites
biggjoee5790    229
Thanks so much man that really helped.. i have some questions though. First of all i wanna say i havent covered exceptions and error handling yet so thats why the program doesnt include any of it ( try statements, except statements, etc). But can you elaborate on how I can print the key and the value of a dictionary separately? when i use a for statement such as:



for name in contacts:
print name



it just prints out the keys without the values. Id like it to display the contents of the dictionary like this...

Mom 112314413
Dad 234324324
etc
etc
etc

can you also elaborate on this..

Quote:

You should pass the contacts-dict as a parameter to your functions. Ex:

def add( contacts ):
contacts[name] = raw_input("Number? ")

This way you could have a personal contactlist, a work one and so on.



I understand exactly what you are trying to achieve.. you want to be able to create different kinds of contacts in the same program.. but i dont understand exactly how you explained it. I know how to pass parameters to a function but i dont get how that would fit here. I apoligize but im pretty new so bear with me if i dont understand right away... and thanks again

Share this post


Link to post
Share on other sites
Kylotan    9854
Quote:
Original post by biggjoee5790
But can you elaborate on how I can print the key and the value of a dictionary separately?


Mapping Types shows some of a dictionary's most useful methods. What you possibly want are the 'items()' instead of just the keys (which you get when iterating over the dictionary directly), so try:

for (name, number) in contacts.items():
print name, number


Or something similar. Each iteration returns a pair, and you 'unpack' that pair into 2 variables, called name and number respectively.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this