#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    2

    Need help with codes (pickling and more)


    Seeking help with an exercise with all stuff jammed together. Pretty confused and really don't know where to go from here. I took close to 3hrs for the below codes . I believe its probably a joke exercise to most of you here.. I have attached the detailed question and my workout codes. Not seeking for exact answers but I would appreciate to get some guidance on whether the codes are going the right way, maybe something I missed out, what I could probably look at next or something. Or if I should just scrap this whole code and restart (hope not). Thanks so much for reading through and helping.

    Question:
    Write program to ask user to either print names from database or add names to database(a file).

    If user choose add database, user should be able to add names to database until he enters -1. All names entered must be stored in a list, when done; this list must be stored in a file.

    If user choose to print names, then list must be loaded from file and list must be printed.

    Hints:
    1. Ask user print or add to database.
    2. Use if statement to respond to either option
    3. write function readNames, use while loop to keep adding names, -1 to stop.
    4. Invoke readName at correct spot.
    5. Write another function pickleObject, which takes an object as a parameter, pickle it and store to a file Exercise1.pkl
    6.Add some code to call pickleObject() to write list of name to disk
    7.1. new function called readFromDatabase. It reads list from file and prints content.
    7.2. write yet another new function called unpickleObject. This should read Exercise1.pkl file and and retrieve stored list.
    7.3. Add some codes to call unpickleObject to receive list of names stored in disk.
    7.4 Write some codes to print names stored by list.
    8. Write some codes to to invoke readFromDatabase().




    Code:
    import pickle 
    print 'Press 1 to load your file:' # (hint 1) 
    print 'Press 2 to add names to your file:' 
    
    userInput2 = 0 
    mylist = [] 
    userInput1 = int(raw_input('Please choose 1 or 2: ')) 
    if userInput1 == 1: 
         unpickleObject() # (Maybe question 7.3) 
    
    if userInput1 == 2: # (hint 2) 
         while userInput2 != -1: 
              def readNames(): # (hint 3) 
                   userInput2 = raw_input('Enter name to add ') 
                   mylist.append(userInput2)  
                   return mylist 
              readNames()#not call it here (hint 4)
     
    def pickleObject(): #( hint 5) 
         myNewFile1 = open('Exercise1.pkl', 'w')                                                
         pickle.dump(userInput2, myNewFile1)
         myNewFile1.close() 
         pickleObject() #not call it here (hint 6) 
    
    def readFromDatabase(): # (hint 7.1) 
         def unpickleObject(): 
              myNewFile2 = open('Exercise1.pkl') 
              myNewFile2 = pickle.load(myNewFile2) 
              myNewFile2.close() return myNewFile2 # (hint 7.2)     unpickleObject()# not call it here (hint 7.3) 
    readFromDatabase()# (hint 8) Hmm what's the use of function within a function here~
    
    print mylist #hmm~ (hint 7.4)
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,856
    Rep Power
    481
    Defining functions within other functions is often a good idea---that's how decorators work. It's not good in your program.

    Start with clean instances of python.

    (After byte compiling your program during which it would find syntax errors) Python evaluates your code from the first line down, executing all the non-indented lines and blocks they may happen to call, as well as the first level indentations in class statements.

    Your source effectively says

    f() #*

    def f():
    #statements

    When python evaluates the line marked with an asterisk it doesn't yet have a definition for f. You ended up with screwy nested function definitions, and since you didn't (I'm sure of this (ha ha)) start with "clean python sessions" your unpickler was left over from an earlier definition.


    Usually modules come in two parts, a definition section followed by an executable part. Excluding comments, to look like:
    Code:
    ''' module doc string with doc tests '''
    
    # imports
    
    #def functions():
        #body
    
    #class c:
    #   definitions important for the class
    
    #executable statements
    Sometimes you'll need to intersperse executable statements between the definitions.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    2
    Hi, tnks for reply. I kind of re-did the work. It seems to work now but little confused about some stuff.

    To recap, the question was to program asking user to choose between print his database(his file) or add names to his database. Added names should be sent to a list which is saved in a file. Choosing printing option will print out this list.

    Believe I'm asking a lot of questions.. Sorry about it but just want to clear it up.. Thanks for helping.

    My queries:

    1. Is it a must to use return key to get this code to work correctly? Cos I didn't use it at all and stayed with using print.

    2. Hint 7.1 and hint 8 - The way it is hinted, I am visualizing a def within a def. But I didn't do it that way and also cant picture how I should go about doing it.

    3. Also for the function pickleObject, I am calling it without any parameter even though the hint asked to use a one parameter (object). I can't picture the need for it..

    4. For the part where the user wants to print out his list of names, it is printed out as a list. ie [1,2,3,4,5,6]. How can I get it to print as follows:

    1
    2
    3
    4
    5
    6

    5. Also, my while loop runs till user enters -1. But I am playing with int on the raw_input. What if I want to add names instead. I gotta remove that int to accept strings which means my while loop will not recognise a -1 and still carry on looping.. How to come around this?

    6. Last query, I want -1 to be used to stop the loop. right now -1 does stop the loop, but also adds the -1 to the list. How to stop it from adding to the list?

    Code:
    import pickle 
    
    print '1.Print names from Database' 
    print '2.Add names to Database' 
    
    mylist = [] 
    
    def readFromDatabase(): # Answer to hint 7.1
        for x in mylist:
            print x
    
    def pickleObject(): #Answer to hint 5 
        myPickleFile = open('Exercise10.pkl', 'w') 
        pickle.dump(mylist, myPickleFile) 
        myPickleFile.close() 
    
    def unpickleObject(): #answer to hint 7.2 
        myUnpickleFile = open('Exercise10.pkl') 
        myUnpickle = pickle.load(myUnpickleFile) 
        myUnpickleFile.close() 
        print myUnpickle #Answer to hint 7.4 
    
    def readNames(): #Answer to hint 3  
        userInput2 = 0 
        while userInput2 != -1: 
            userInput2 = int(raw_input('Please enter number to add: ')) 
            mylist.append(userInput2) 
            print mylist 
        pickleObject() #Answer to hint 6 
    
    userInput1 = int(raw_input('Please select 1 or 2: '))# Answer to hint 1 
    
    if userInput1 == 1: #Aswer to hint 2 
        unpickleObject() #Answer to hint 7.3 
        readFromDatabase() #Answer to hint 8
    
    elif userInput1 == 2: 
        readNames() #Answer to hint 4 
    
    else: 
        print 'Sorry invalid option chosen!'
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,856
    Rep Power
    481

    ignore stupid hints


    (more likely they aren't clear. They may represent good thought.) This effort much better. The other was nearly unreadable.
    Code:
    '''
        to append data unpickle, and continue using that list.
    '''
    
    import pickle
    
    print '1.Print names from Database'
    print '2.Add names to Database'
    
    mylist = []
    
    def pickleObject(): #Answer to hint 5
        with open('Exercise10.pkl', 'w') as myPickleFile:   # ################ look up with context
            pickle.dump(mylist, myPickleFile)
    
    def unpickleObject(): #answer to hint 7.2################return the value more useful than print it.
        with open('Exercise10.pkl') as myUnpickleFile:
            myUnpickle = pickle.load(myUnpickleFile)
        return myUnpickle #Answer to hint 7.4
    
    def readNames(): #Answer to hint 3
        userInput2 = 0
        while userInput2 != '-1':               ################# consider -1 as a string.
            userInput2 = raw_input('Please enter names to add: ')
            mylist.append(userInput2)
            print mylist
        if mylist[-1] == '-1':                  ################ Don't want the final value?  Get rid of it!
            del mylist[-1]
        pickleObject() #Answer to hint 6
    
    userInput1 = int(raw_input('Please select 1 or 2: '))# Answer to hint 1
    
    if userInput1 == 1: #Aswer to hint 2
        print(unpickleObject()) #Answer to hint 7.3################print the value here
    
    elif userInput1 == 2:
        readNames() #Answer to hint 4
    
    else:
        print 'Sorry invalid option chosen!'
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    2
    Hi,

    kinda digested your adjusted codes. You have added 3 new keywords which am not familiar with. del / as / with. I believe del is pretty straight forward. I looked up with and as. From my understanding, 'with' closes the block of codes, 'as' formed the variable. (Hope I interpret it right). Trying to see if I can still achieve same results without using these 3 keys. In any case, learnt something new. Tnks.

    Regarding the difference between return and print, guess I gotta really do more reading up cos can't picture the difference.

    To clarify, I don't get what you meant by the comment # look up with context? Thanks.
  10. #6
  11. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,856
    Rep Power
    481
    The "with" statement implements "context". It's a python3 idea. Sure, your "open" ... "close" works fine.

    You don't have to del from the list. You could avoid enlisting it.

    if name != '-1':
    LIST.append(name)


    Instead of del, you could write (which also deletes the last element).

    LIST = LIST[:-1]

    and it works with empty lists.
    >>> [][:-1]
    []



    Suppose, never mind. You wrote this function:
    Code:
    def unpickleObject(): #answer to hint 7.2################return the value more useful than print it.
        with open('Exercise10.pkl') as myUnpickleFile:
            myUnpickle = pickle.load(myUnpickleFile)
        return myUnpickle #Answer to hint 7.4
    If your unpickleObject function didn't return myUnpickle then you couldn't use the value.
    [code]Code tags[/code] are essential for python code and Makefiles!
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    2
    Have a better pic now. I slightly reverted back by removing 'with' and 'as'. Still keeping del which I felt was better.

    Thanks for help.

    Code:
    import pickle 
    
    print '1.Print names from Database' 
    print '2.Add names to Database' 
    
    mylist = [] 
    
    def pickleObject(): #Answer to hint 5 
         myPickleFile = open('Exercise5.pkl', 'w') 
         pickle.dump(mylist, myPickleFile) 
         myPickleFile.close() 
    
    def unpickleObject(): #answer to hint 7.2 
         myUnpickleFile = open('Exercise5.pkl') 
         myUnpickle = pickle.load(myUnpickleFile)                                                                       
         myUnpickleFile.close()
         return myUnpickle #Answer to hint 7.4 
    
    def readNames(): #Answer to hint 3 
         userInput2 = 0 
         while userInput2 != '-1': 
              userInput2 = (raw_input('Please enter name to add: ')
              mylist.append(userInput2) 
         if mylist[-1] == '-1': 
               del mylist[-1] 
         pickleObject() #Answer to hint 6 
    
    userInput1 = (raw_input('Please select 1 or 2: '))# Answer to hint 1 
    
    if userInput1 == '1': #Aswer to hint 2 
         print unpickleObject() #Answer to hint 7.3 
    
    elif userInput1 == '2': 
         readNames() #Answer to hint 4 
    
    else: 
         print 'Sorry', userInput1 ,'is not a valid option.'

IMN logo majestic logo threadwatch logo seochat tools logo