Jump to content

Simple Problem

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
10 replies to this topic

#1
jivkoss

jivkoss

    Newbie

  • Members
  • PipPip
  • 28 posts
Hello,
At the end of the book 'A Byte of Python' I'm asked to do the following: Create your own command-line address-book program using which you can browse, add, modify, delete or search for your contacts such as friends, family and colleagues and their information such as email addresses and/or phone number. Details must be stored for later retrieval. Hint: Create a class to represent the person's information. Use a dictionary to store person objects with their name as the key. Use the pickle module to store the objects persistently on your hard disk. Use the dictionary built-in methods to add, delete and modify the persons. And here is the code I come up with after 10 minutes of thinking:
class Zhivko:

    age = 20

    occupation = 'student'


class Hristo:

    age = 21

    occupation = 'worker'


class Margata:

    age = 21

    occupation = 'local fool'


dictionary = {'zhivko' : 'student',

              'hristo' : 'worker',

              'margata': 'local fool'

              }


print Zhivko.age


print('Zhivko is a ',dictionary['zhivko'])


I just want to know if I'm on the right way of solving that? And also do I have to make the program in such a way that when ran in Command Prompt the user can browse, add, delete and modify the dictionary by for example typing a command 'add' for adding and then typing the name and the occupation of the person, and the python script has to be written in such a way that after the user does that it automatically goes into the dictionary?

#2
jivkoss

jivkoss

    Newbie

  • Members
  • PipPip
  • 28 posts
2nd Version: Whats wrong with this code and why it does not executes the if block?
dictionary = {'zhivko' : 'student',
              'hristo' : 'worker',
              'margata': 'local fool'
              }


print('Zhivko is a ',dictionary['zhivko'])
print("if you want to see the dictionary type 'browse' and press enter")
i = input("enter smth: ")
if i == 'browse':
    print dictionary
else:
    print('you are not interested in in that i suppose')

input("Press<enter>")


#3
Sapman

Sapman

    Newbie

  • Members
  • PipPip
  • 20 posts
Change
 i = input("enter smth: ")
to -->
 i = raw_input("enter smth: ")


#4
jivkoss

jivkoss

    Newbie

  • Members
  • PipPip
  • 28 posts
Here is my solution to the problem at the end of the book "A Byte of Python":
dy = { 'Zhivko' : 'student, zihvko@gmail.com',
       'Hristo' : 'worker, hristo@yahoo.co.uk',
       'Margata': 'local fool, marga@abv.bg',
       }

def inst():
    print('''Type 'browse' to see the address book,
'del + name' to delete a contact,
'add' and follow the instructions to add a contact
or type 'quit' to exit
''')
inst()
while True:  
    i = input("Enter your choice here: ")

    if i == 'browse':
        print ('', dy)

    elif i == 'del Zhivko':
        del dy['Zhivko']
        print('Zhivko was deleted from the address book')
    elif i == 'del Hristo':
        del dy['Hristo']
        print('Hristo was deleted from the address book')
    elif i == 'del Margata':
        del dy['Margata']
        print('Margata was deleted from the address book')
    elif i == 'add':
        n = input('Enter the name of the person: ')
        o = input("Enter the occupation folloed by the email seperated by',': ")
        dy[n] = o
    elif i == 'quit':
        break
    else:
        print('You have entered am invalid command please read the instructions and try again')
        inst()
print('Done')
input("Press <enter> to exit")

    


It works fine when I run it in the command prompt, but however I'm not satisfied with the solution because I didn't use class to represent the person's information as the guy who wrote the book told in the hint. If anyone has an idea how to use class to improve my program please tell me! Cos i plan to make a GUI for it and sell this baby for millions:laugh:

#5
manux

manux

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 234 posts
It would be funnier if you could delete the persons you added, because here the only persons you can delete are the original 3.

A hint, use str.split, example:
>>> a = "del BillGates"
>>> b = a.split(" ")
>>> b
['del', 'BillGates']
>>> print b[0]=="del"
True


#6
jivkoss

jivkoss

    Newbie

  • Members
  • PipPip
  • 28 posts
I was on vacation thats why i didn't reply as soon as possible. I'm sorry but i can't figure out how to delete persons i have added. I understood your code using the split method but i don't know how to use it. Can you give me another hint, please?

#7
Excited

Excited

    Newbie

  • Members
  • PipPip
  • 27 posts
Did you even read the rest of the book? (note: I haven't so I don't know how bad it must be).

#8
jivkoss

jivkoss

    Newbie

  • Members
  • PipPip
  • 28 posts
I read the whole book it's a tutorial book 110 pages, I read it for 5 days and this problem for the address book is at the end of the book, the guy who wrote it said that if we are able to do this address book we can claim to be a python programmer.

#9
fixion

fixion

    Newbie

  • Members
  • Pip
  • 4 posts

I figured I'd post my old solution to this up here, as well. There might be something in it that you can use. Consider it my first contribution to CodeCall.

I know the code might not be really great, but bear in mind this was my first 'real' Python program.


# Filename: addrbook.py

import pickle

import os


savefile = "addrbook.data"


class AddressBook:

    index = {}



    def __init__(self):

        raise NotImplementedError('AddressBook is not to be instantiated.')


    def search():

        '''Search for the occurrence of a key within index'''

        contactName = raw_input("Enter the name of the person to search for\n\

                                 --> ")

        if contactName in AddressBook.index:

            print("{0}\n".format(AddressBook.index[contactName]))

        else:

            print("The person you searched for does not exist.\n")


    def add():

        '''Obtain information for new contact from user and add to index.'''

        contactName = raw_input("Enter the name of the person to add.\n--> ")

        contactInfo = raw_input("Enter the information for your friend\n--> ")

        AddressBook.index[contactName] = contactInfo + "\n"

        print("Contact successfully added!\n")


    def remove():

        '''If the contact specified exists within index, remove them.'''

        contactName = raw_input("Enter the name of the contact to remove.\

                                 \n--> ")

        if contactName in AddressBook.index:

            AddressBook.index.pop([contactName])

            print("Contact successfully removed!\n")

        else:

            print("Contact could not be found.\n")


    def browse():

        '''Print a list of all the keys in index.'''

        print()

        for i in AddressBook.index:

            print(i)

        print("The above are all the contacts you have listed.\n")


def main():

    '''Main function to handle user interaction.'''

    # If the savefile already exists, load its contents into index.

    if os.path.isfile(savefile):

        with open(savefile, 'rb') as f:

            AddressBook.index = pickle.load(f)


    #Inform the user of the actions he/she may take.

    print("Search Contacts .... S")

    print("Add Contact ........ A")

    print("Remove Contact ..... R")

    print("Browse Contacts .... B")

    print("Quit ............... Q\n")


    #Run the program continuously, until specified to stop by user.       

    while True:

        opt = raw_input("Which action would you like to take?: ")[0]

        #Check which command the user placed and act accordingly.

        if opt == 'S':

            AddressBook.search()

        elif opt == 'A':

            AddressBook.add()

        elif opt == 'R':

            AddressBook.remove()

        elif opt == 'B':

            AddressBook.browse()

        elif opt == 'Q':

            #If the save file already exists, delete it.

            if os.path.isfile(savefile):

                os.remove(savefile)

            with open(savefile, 'wb') as f:

                #Index is safely saved within a clean, new file.

                pickle.dump(AddressBook.index, f)

            break

        else:

            print("invalid input.")


###MAIN FUNCTION###

if __name__ == '__main__':

    main()



#10
jivkoss

jivkoss

    Newbie

  • Members
  • PipPip
  • 28 posts
It looks beautiful but it's not working for me. Which version of python do you use? I use 2.7. When i type 'S' the program quits.

#11
fixion

fixion

    Newbie

  • Members
  • Pip
  • 4 posts
I would have coded this in 2.6.5 if I am not mistaken.