user2306249
user2306249

Reputation: 69

Python Phonebook program

I have this program, and it is almost perfect but I need the dictionary to print on separate lines like so:

Please enter a name (or just press enter to end the input): Tom
Please enter Tom's phone: 555-5555

Please enter a name (or just press enter to end the input): Sue
Please enter Sue's phone: 333-3333

Please enter a name (or just press enter to end the input): Ann
Please enter Ann's phone: 222-2222

Please enter a name (or just press enter to end the input): 
Thank you. 

Your phonebook contains the following entries:

Sue 333-3333

Tom 555-5555

Ann 222-2222  

Here is my code:

def main():

phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
    number = input("Please enter number: ")
    phoneBook[name] = number
    name = input("Please enter a name(or press enter to end input): ")
    if name == '':
        print("Thank You!")

print("Your phonebook contains the following entries:\n",phoneBook)


main()

Upvotes: 2

Views: 7623

Answers (5)

user13068413
user13068413

Reputation: 1

my_dictionary = {}
while True:
    name = str(input("Enter a name: "))
    if name == "":
        break
    elif name in my_dictionary:
        print "Phone Number: " + my_dictionary[name]
    else:
        phone_number = input("Enter this person's number: ")
        my_dictionary[name] = phone_number
print my_dictionary

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174624

You can use format() to make your life easy:

for i in phoneBook.iteritems():
    print("{0} {1}".format(*i))

Upvotes: 1

thkang
thkang

Reputation: 11543

if you dont want to write codes yourself, pprint could be an option:

import pprint

....

print("Your phonebook contains the following entries:\n")
pprint.pprint(phoneBook)

Upvotes: 2

Nolen Royalty
Nolen Royalty

Reputation: 18633

Loop through the entries in your phonebook and print them one at a time:

for name, number in phoneBook.items():
    print ("%s %s" % (name, number))

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250911

something like this:

strs = "\n".join( " ".join((name,num)) for name,num in phoneBook.items() )
print("Your phonebook contains the following entries:\n",strs)

Upvotes: 1

Related Questions