help with append and delete

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pythonnoob
    New Member
    • Oct 2007
    • 9

    help with append and delete

    Hello everyone. New to python as well as this forum, but i must say ive learned a but already reading through some posts. Seems to be a pretty helpful community here.

    Before i post a question ill give you a little background. I have done programming in the past in Basic, VB, and a little C. I am not much of a programmer, its more of a hobby/curiosity.

    The following code is not mine, i am trying to modify a template of a mock database. The options in the database are 0. Exit 1. Query 2. Append. 3 Delete. I am trying to use functions here, and they are defined at the top of the program. the code is as follows:


    Code:
    def query(course, grade):
        courseindex=database[0].index(course)
        for record in range(1,len(database),1):
            if database[record][courseindex]==grade:
                print database[record][0]
        print("\n")
        raw_input("press enter to continue\n\n\n")
    
    def append(name, math, English, Physics, Chemistry):
        print("The append function is to be written")
        raw_input("press enter to continue\n\n\n")
    
    def delete(ID):
        print("The delete function is to be written")
        raw_input("press enter to continue\n\n\n")
        
    #main
    #global variable
    database=[["name","ID","Math","English","Physics","Chemistry"]]
    database+=[["Tom",1,"A","B","B","C"]]
    database+=[["Chen",2,"B","C","D","A"]]
    database+=[["John",3,"C","B","A","D"]]
    database+=[["Andres",4,"D","A","C","B"]]
    Current_ID=5
    #global variable
    
    
        
    
    choice = None
    while choice != "0":
        
        for record in range(0, len(database),1):
            row=""
            for attribute in range(0,len(database[record]),1):
                row+=str(database[record][attribute])+","
                
            print row+"\n"
    
        
        print \
        """
        Welcome to Mini Database
        
        0 - Exit
        1 - Query
        2 - Append
        3 - Delete
    
        """
        
        choice = raw_input("Choice: ")
        # exit
        if choice == "0":
            print "Good-bye."
    
        # query
        elif choice == "1":
            query(raw_input("What course you want to query?"),
                  raw_input("What grade you want to query?"))
    
        elif choice=="2":
            append(raw_input("What is the student's name?"),
                   raw_input("What is the student's grade for Math?(A/B/C/D/F)"),
                   raw_input("What is the student's grade for English?(A/B/C/D/F)"),
                   raw_input("What is the student's grade for Physics?(A/B/C/D/F)"),
                   raw_input("What is the student's grade for Chemistry?(A/B/C/D/F)"))
    
        elif choice=="3":
            delete(int(raw_input("What is the student's ID?")))
            
        # some unknown choice
        else:
            print "Sorry, but", choice, "isn't a valid choice."
    
    
    
    raw_input("press enter to finish the program")

    I am pretty sure the query function is correct, but i am not sure how to append to a database or to delete?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    I think it would be better to use a dictionary for your database.

    [code=Python]>>> db = {"name": ["ID","Math","En glish","Physics ","Chemistr y"]}
    >>> db["Tom"] = [1,"A","B","B"," C"]
    >>> db
    {'name': ['ID', 'Math', 'English', 'Physics', 'Chemistry'], 'Tom': [1, 'A', 'B', 'B', 'C']}
    >>> del db["Tom"]
    >>> db
    {'name': ['ID', 'Math', 'English', 'Physics', 'Chemistry']}
    >>> [/code]

    Comment

    • pythonnoob
      New Member
      • Oct 2007
      • 9

      #3
      I see what you are saying here, but this code was already written. I am trying to modify someone elses code and create functions with what is already give.

      Comment

      • KaezarRex
        New Member
        • Sep 2007
        • 52

        #4
        Here's a start...
        [CODE=python]def query(course, grade):
        courseindex=dat abase[0].index(course)
        for record in database:#I changed this slightly
        if record[courseindex]==grade:
        print record[0]
        print("\n")
        raw_input("pres s enter to continue\n\n\n" )

        def append(name, Math, English, Physics, Chemistry):
        global database, Current_ID
        #Change database and Current_ID appropriately
        raw_input("pres s enter to continue\n\n\n" )

        def delete(ID):
        global database#global allows you to modify variables outside the function
        ID_index = 1
        #This will look much like the loop in query, but when
        #you find the right record, delete it and break
        raw_input("pres s enter to continue\n\n\n" )[/CODE]

        Comment

        • pythonnoob
          New Member
          • Oct 2007
          • 9

          #5
          I see the changes you made to the first function. Would what i had originally have worked?

          Comment

          • KaezarRex
            New Member
            • Sep 2007
            • 52

            #6
            Originally posted by pythonnoob
            I see the changes you made to the first function. Would what i had originally have worked?
            It worked fine before, but you were going out of your way to iterate over the indexes of the database, when you can simply iterate over the elements themselves. It's really up to you.

            Comment

            • pythonnoob
              New Member
              • Oct 2007
              • 9

              #7
              That makes sense. Im sure this is an easy function, but i dont see how to use append. By using global, i see that i can modify the database, but i dont see how i could append what i need to where i need to?

              Comment

              • KaezarRex
                New Member
                • Sep 2007
                • 52

                #8
                I'd recommend appending a new person to the list the same way the pre-written code did when it setup the database.
                [CODE=python]database += [[name, Current_ID, Math, English, Physics, Chemistry]][/CODE]
                That will append the new entry to the end of the list. It shouldn't matter what order the database list is in, as long as that first entry with the category names stays the first entry.
                Don't forget to increment Current_ID every time you add someone so each person's ID stays unique.

                Comment

                • bartonc
                  Recognized Expert Expert
                  • Sep 2006
                  • 6478

                  #9
                  First, the greeting: WELCOME! I really appreciate your introduction and sentiment (and your use of CODE tags). [CODE=python]>>> # a few OOP basics:
                  >>> aListObj = ['item1', 'item2', 'item3'] # create the object
                  >>> aListObj.index( 'item1') # call a METHOD of the object
                  0
                  >>> aListObj.index( 'item2') # call a METHOD of the object
                  1
                  >>> aListObj.remove ('item2') # call a METHOD of the object
                  >>> print aListObj
                  ['item1', 'item3']
                  >>> aDictObj = {'item1':(1, 2, 3), 'item2':(1, 2, 3), 'item3':(1, 2, 3)} # create the dictionary object
                  >>> aDictObj.pop('i tem2') # call a METHOD of the object
                  (1, 2, 3)
                  >>> print aDictObj
                  {'item3': (1, 2, 3), 'item1': (1, 2, 3)}
                  >>> [/CODE]

                  Comment

                  • pythonnoob
                    New Member
                    • Oct 2007
                    • 9

                    #10
                    Thanks for your help, i think i got it!

                    [CODE=python]# database
                    # Query on database

                    def query(course, grade):
                    courseindex=dat abase[0].index(course)
                    for record in range(1,len(dat abase),1):
                    if database[record][courseindex]==grade:
                    print database[record][0]
                    print("\n")
                    raw_input("pres s enter to continue\n\n\n" )

                    def append(name, Math, English, Physics, Chemistry):
                    global database, Current_ID
                    database.append ([name, Current_ID, Math, English, Physics, Chemistry])
                    Current_ID = Current_ID+1
                    raw_input("pres s enter to continue\n\n\n" )
                    print database
                    def delete(ID):
                    global database, Current_ID
                    for record in range(1,len(dat abase),1):
                    if database[record][1]==ID:
                    erased=record
                    database.pop(er ased)
                    raw_input("pres s enter to continue\n\n\n" )

                    #main
                    #global variable
                    database=[["name","ID","Ma th","English"," Physics","Chemi stry"]]
                    database+=[["Tom",1,"A","B" ,"B","C"]]
                    database+=[["Chen",2,"B","C ","D","A"]]
                    database+=[["John",3,"C","B ","A","D"]]
                    database+=[["Andres",4,"D", "A","C","B"]]
                    Current_ID=5
                    #global variable




                    choice = None
                    while choice != "0":

                    for record in range(0, len(database),1 ):
                    row=""
                    for attribute in range(0,len(dat abase[record]),1):
                    row+=str(databa se[record][attribute])+","

                    print row+"\n"


                    print \
                    """
                    Welcome to Mini Database

                    0 - Exit
                    1 - Query
                    2 - Append
                    3 - Delete

                    """

                    choice = raw_input("Choi ce: ")
                    # exit
                    if choice == "0":
                    print "Good-bye."

                    # query
                    elif choice == "1":
                    query(raw_input ("What course you want to query?"),
                    raw_input("What grade you want to query?"))

                    elif choice=="2":
                    append(raw_inpu t("What is the student's name?"),
                    raw_input("What is the student's grade for Math?(A/B/C/D/F)"),
                    raw_input("What is the student's grade for English?(A/B/C/D/F)"),
                    raw_input("What is the student's grade for Physics?(A/B/C/D/F)"),
                    raw_input("What is the student's grade for Chemistry?(A/B/C/D/F)"))

                    elif choice=="3":
                    delete(int(raw_ input("What is the student's ID?")))

                    # some unknown choice
                    else:
                    print "Sorry, but", choice, "isn't a valid choice."



                    raw_input("pres s enter to finish the program")
                    [/CODE]


                    any input would be great.

                    thanks again people!
                    Last edited by bartonc; Oct 24 '07, 09:36 PM. Reason: Added =python to code tags

                    Comment

                    • KaezarRex
                      New Member
                      • Sep 2007
                      • 52

                      #11
                      Originally posted by pythonnoob
                      Thanks for your help, i think i got it!

                      ...

                      any input would be great.

                      thanks again people!
                      That looks great. Here's what I had originally thought you could do for the delete function, but once again, either way works perfectly fine.
                      [CODE=python]def delete(ID):
                      global database, Current_ID
                      for record in range(1,len(dat abase),1):
                      if database[record][1]==ID:
                      database.pop(re cord)
                      break #only saves time if your database is huge
                      raw_input("pres s enter to continue\n\n\n" )[/CODE]

                      Comment

                      Working...