473,895 Members | 2,377 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help with append and delete

9 New Member
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:

Expand|Select|Wrap|Line Numbers
  1. def query(course, grade):
  2.     courseindex=database[0].index(course)
  3.     for record in range(1,len(database),1):
  4.         if database[record][courseindex]==grade:
  5.             print database[record][0]
  6.     print("\n")
  7.     raw_input("press enter to continue\n\n\n")
  9. def append(name, math, English, Physics, Chemistry):
  10.     print("The append function is to be written")
  11.     raw_input("press enter to continue\n\n\n")
  13. def delete(ID):
  14.     print("The delete function is to be written")
  15.     raw_input("press enter to continue\n\n\n")
  17. #main
  18. #global variable
  19. database=[["name","ID","Math","English","Physics","Chemistry"]]
  20. database+=[["Tom",1,"A","B","B","C"]]
  21. database+=[["Chen",2,"B","C","D","A"]]
  22. database+=[["John",3,"C","B","A","D"]]
  23. database+=[["Andres",4,"D","A","C","B"]]
  24. Current_ID=5
  25. #global variable
  30. choice = None
  31. while choice != "0":
  33.     for record in range(0, len(database),1):
  34.         row=""
  35.         for attribute in range(0,len(database[record]),1):
  36.             row+=str(database[record][attribute])+","
  38.         print row+"\n"
  41.     print \
  42.     """
  43.     Welcome to Mini Database
  45.     0 - Exit
  46.     1 - Query
  47.     2 - Append
  48.     3 - Delete
  50.     """
  52.     choice = raw_input("Choice: ")
  53.     # exit
  54.     if choice == "0":
  55.         print "Good-bye."
  57.     # query
  58.     elif choice == "1":
  59.         query(raw_input("What course you want to query?"),
  60.               raw_input("What grade you want to query?"))
  62.     elif choice=="2":
  63.         append(raw_input("What is the student's name?"),
  64.                raw_input("What is the student's grade for Math?(A/B/C/D/F)"),
  65.                raw_input("What is the student's grade for English?(A/B/C/D/F)"),
  66.                raw_input("What is the student's grade for Physics?(A/B/C/D/F)"),
  67.                raw_input("What is the student's grade for Chemistry?(A/B/C/D/F)"))
  69.     elif choice=="3":
  70.         delete(int(raw_input("What is the student's ID?")))
  72.     # some unknown choice
  73.     else:
  74.         print "Sorry, but", choice, "isn't a valid choice."
  78. 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?
Oct 24 '07 #1
10 2079
2,851 Recognized Expert Moderator Specialist
I think it would be better to use a dictionary for your database.

Expand|Select|Wrap|Line Numbers
  1. >>> db = {"name": ["ID","Math","English","Physics","Chemistry"]}
  2. >>> db["Tom"] = [1,"A","B","B","C"]
  3. >>> db
  4. {'name': ['ID', 'Math', 'English', 'Physics', 'Chemistry'], 'Tom': [1, 'A', 'B', 'B', 'C']}
  5. >>> del db["Tom"]
  6. >>> db
  7. {'name': ['ID', 'Math', 'English', 'Physics', 'Chemistry']}
  8. >>> 
Oct 24 '07 #2
9 New Member
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.
Oct 24 '07 #3
52 New Member
Here's a start...
Expand|Select|Wrap|Line Numbers
  1. def query(course, grade):
  2.     courseindex=database[0].index(course)
  3.     for record in database:#I changed this slightly
  4.         if record[courseindex]==grade:
  5.             print record[0]
  6.     print("\n")
  7.     raw_input("press enter to continue\n\n\n")
  9. def append(name, Math, English, Physics, Chemistry):
  10.     global database, Current_ID
  11.     #Change database and Current_ID appropriately
  12.     raw_input("press enter to continue\n\n\n")
  14. def delete(ID):
  15.     global database#global allows you to modify variables outside the function
  16.     ID_index = 1
  17.     #This will look much like the loop in query, but when
  18.     #you find the right record, delete it and break 
  19.     raw_input("press enter to continue\n\n\n")
Oct 24 '07 #4
9 New Member
I see the changes you made to the first function. Would what i had originally have worked?
Oct 24 '07 #5
52 New Member
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.
Oct 24 '07 #6
9 New Member
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?
Oct 24 '07 #7
52 New Member
I'd recommend appending a new person to the list the same way the pre-written code did when it setup the database.
Expand|Select|Wrap|Line Numbers
  1. database += [[name, Current_ID, Math, English, Physics, Chemistry]]
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.
Oct 24 '07 #8
6,596 Recognized Expert Expert
First, the greeting: WELCOME! I really appreciate your introduction and sentiment (and your use of CODE tags).
Expand|Select|Wrap|Line Numbers
  1. >>> # a few OOP basics:
  2. >>> aListObj = ['item1', 'item2', 'item3'] # create the object
  3. >>> aListObj.index('item1')  # call a METHOD of the object
  5. >>> aListObj.index('item2')  # call a METHOD of the object
  6. 1
  7. >>> aListObj.remove('item2')  # call a METHOD of the object
  8. >>> print aListObj
  9. ['item1', 'item3']
  10. >>> aDictObj = {'item1':(1, 2, 3), 'item2':(1, 2, 3), 'item3':(1, 2, 3)} # create the dictionary object
  11. >>> aDictObj.pop('item2')  # call a METHOD of the object
  12. (1, 2, 3)
  13. >>> print aDictObj
  14. {'item3': (1, 2, 3), 'item1': (1, 2, 3)}
  15. >>> 
Oct 24 '07 #9
9 New Member
Thanks for your help, i think i got it!

Expand|Select|Wrap|Line Numbers
  1. # database
  2. # Query on database
  4. def query(course, grade):
  5.     courseindex=database[0].index(course)
  6.     for record in range(1,len(database),1):
  7.         if database[record][courseindex]==grade:
  8.             print database[record][0]
  9.     print("\n")
  10.     raw_input("press enter to continue\n\n\n")
  12. def append(name, Math, English, Physics, Chemistry):
  13.     global database, Current_ID
  14.     database.append([name, Current_ID, Math, English, Physics, Chemistry])
  15.     Current_ID = Current_ID+1
  16.     raw_input("press enter to continue\n\n\n")
  17.     print database
  18. def delete(ID):
  19.     global database, Current_ID
  20.     for record in range(1,len(database),1):
  21.         if database[record][1]==ID:
  22.                 erased=record
  23.     database.pop(erased)
  24.     raw_input("press enter to continue\n\n\n")
  26. #main
  27. #global variable
  28. database=[["name","ID","Math","English","Physics","Chemistry"]]
  29. database+=[["Tom",1,"A","B","B","C"]]
  30. database+=[["Chen",2,"B","C","D","A"]]
  31. database+=[["John",3,"C","B","A","D"]]
  32. database+=[["Andres",4,"D","A","C","B"]]
  33. Current_ID=5
  34. #global variable
  39. choice = None
  40. while choice != "0":
  42.     for record in range(0, len(database),1):
  43.         row=""
  44.         for attribute in range(0,len(database[record]),1):
  45.             row+=str(database[record][attribute])+","
  47.         print row+"\n"
  50.     print \
  51.     """
  52.     Welcome to Mini Database
  54.     0 - Exit
  55.     1 - Query
  56.     2 - Append
  57.     3 - Delete
  59.     """
  61.     choice = raw_input("Choice: ")
  62.     # exit
  63.     if choice == "0":
  64.         print "Good-bye."
  66.     # query
  67.     elif choice == "1":
  68.         query(raw_input("What course you want to query?"),
  69.               raw_input("What grade you want to query?"))
  71.     elif choice=="2":
  72.         append(raw_input("What is the student's name?"),
  73.                raw_input("What is the student's grade for Math?(A/B/C/D/F)"),
  74.                raw_input("What is the student's grade for English?(A/B/C/D/F)"),
  75.                raw_input("What is the student's grade for Physics?(A/B/C/D/F)"),
  76.                raw_input("What is the student's grade for Chemistry?(A/B/C/D/F)"))
  78.     elif choice=="3":
  79.         delete(int(raw_input("What is the student's ID?")))
  81.     # some unknown choice
  82.     else:
  83.         print "Sorry, but", choice, "isn't a valid choice."
  87. raw_input("press enter to finish the program")

any input would be great.

thanks again people!
Oct 24 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

by: matt | last post by:
I have compiled some code, some written by me, some compiled from various sources online, and basically i've got a very simple flat file photo gallery. An upload form, to upload the photos and give them a caption, storing the caption and filename in a text file. It's a bit buggy when removing the photos and captions from the file, and also in displaying them on the delete page. you can see it in action at www.4am.com.au/gallery/upload.php...
by: Christian Christmann | last post by:
Hi, in the past I always appreciated your help and hope that you also can help me this time. I've spent many many hours but still can't solve the problem by myself and you are my last hope. I've a program which is using self-written double-linked lists as a data structure. The template list consists of list elements and the list itself linking the list elements.
by: tym | last post by:
HELP!!! I'm going round the twist with this... I have a VB6 application which is using DAO to access a database (Please - no lectures on ADO, I know what I'm doing with DAO!!) Ok, problem is this.... importing a large csv file (189000 lines, 7 fileds per line)
by: Ryan Case | last post by:
I am using Access to store data from a CAD program. We then in turn have another program pull data from Access to drive computerized saws. In order to get the data from the CAD program to Access, a report must be ran within the CAD program. This generates a .rpt comma delim value file. I have been putting this into excel and then creating a linked table withing Access out of the excel file. A simple delete query and then append query...
by: jw | last post by:
i have a program it has a list of random numbers and my aim is to add the nodes in another list the nodes will be in an order at the new link list #include<iostream> #include<cmath> using namespace std; class Node{ private:
by: Rahul | last post by:
Hi Everybody I have some problem in my script. please help me. This is script file. I have one *.inq file. I want run this script in XML files. But this script errors shows . If u want i am attach this script files and inq files. I cant understand this error. Please suggest me. You can talk with my yahoo id b_sahoo1@yahoo.com. Now i am online. Plz....Plz..Plz...
by: MN | last post by:
I have to import a tab-delimited text file daily into Access through a macro. All of the data needs to be added to an existing table. Some of the data already exists but may be updated by the imported text file. I can update the data through an update query or append the entire import table through an append query. Is there a way to combine the two so that I can update existing records and append only new records (without duplicating...
by: allingame | last post by:
Need help with append and delete duplicates I have tables namely 1)emp, 2)time and 3)payroll TABLE emp ssn text U]PK name text
by: jinalpatel | last post by:
I have two tables. tblClass and tblWithdrawn. On my main form(bound to tblClass) I have several data entry fields like Date withdrawn, Status (active or withdrawn) Date Classified etc. Also there is one command button called cmdAppendDelete. On click this command button two queries are run .(append and delete) When user selects Status = Withdrawn and enter the "Date Withdrawn", he has to click on this command button. Append query...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.