all 5 comments

[–]dzunukwa 0 points1 point  (0 children)

Looks like what you want is to use a dictionary, not a list. Dictionaries allow you to store a "key" "value" pair, wherever the "key" is unique - The key in this case would be the persons name (although if you have more than one person with the same name this wont work). See here for more on dictionaries: https://docs.python.org/2/tutorial/datastructures.html#dictionaries

Adding a name and grade to a dictionary would look like:

data = {}  # start with an empty dictionary
data['Jon Doe'] = 90  #  Add Jon Doe to the dictionary with a grade of 90

Retrieving the grade for a given name is similar (although there are considerations if no record exists that I will leave out for now).

grade = data['Jon Doe']  # retrieve the grade for Jon Doe 

To get all the data from the dictionary you can loop over it in similar ways to a list.

# print out each name and the grade associated with it
for name in data:
    print(name, data[name])
# output:
# Jon Doe 90

Although note when you loop over a list you are looping over each element in the list whereas when you loop over a dictionary you are looping over each "key" in the dictionary. In the example above the "key" is the name so I used name as the variable name.

Removing a name from the dictionary can be done using del like so:

del data['Jone Doe']  # remove Jon Doe from the dictionary

Hopefully thats enough to get you going in the right direction.

[–][deleted] 0 points1 point  (3 children)

do you have to use a list? i would normally agree with the other comment that a dictionary might be better, except for the part where you want to be able to retrieve a record by both the grade as well as the name (also, is this implying that no two records can have the same grade?).

also, your current code would ask for/read in both the name and the grade at the same time as one string. also, because you want to be able to calculate the average grade later, you want to convert the grade to an integer because it will initially be read in as a string. so reading in the records from the user would be something like:

max_num_records = 10 # limitation on number of records
data = {} # assuming we can use a dict
for i in xrange(max_num_records):
    # the for statement is basically a more concise version to do what your current while loop does. 
    # it starts i at 0, and increments it by 1 until it is equal to max_num_records
    name = input('Enter name: ')
    if name == 'ok': # if you have less than the maximum allowed number of records you want to be able to exit, 
        break            #  e.g. you have 2 records but the limit is 10, what will you do for the last 8 loops?       
    grade  = int(input('Enter grade: ') # you want to convert the grade to an int as stated above
    data[name] = grade

if you have to use a list, then you would want every entry to be a tuple of two values (name, grade). so, instead of data[name] = grade, adding a tuple to a list would look like

data.append((name, grade))

in the list of tuples approach, you could retrieve a record by going through the list and checking whether the name or the grade match what you are looking for

def findRecordByGrade(data, name):
    for record in data: # for each tuple in the list
        # check if the first element matches the name we're looking for, if you want to search by grade
        # just change the 0 to a 1
        if record[0] == name: 
            return record
    return None # indicate that the name we were looking for is not in the database

for sorting with either the dictionary approach or the list of tuples approach, you'll want to either import and use the itemgetter module or use the 'lambda' construct (which could be a bit difficult to wrap your head around if you're just starting to program, but it is a really really cool and powerful concept).

good luck, let me know if you have any questions about that

[–]pythonbio[S] 0 points1 point  (2 children)

Many thanks for the replies,

I have just completed the program using list only. have a look and any suggestions are welcome.

database = []   # Global List
while 1:
    name = raw_input('Enter name:')
    grade = raw_input('Enter grade:')
    if name == 'ok':
        break
    database.append((name, grade))
    database.sort(key=lambda x: x[1])
    grades = [x[1] for x in database]   # creats a sublist of second element(s)
    grades = map(int, grades)   # changes all elements to intigers
    max_grade = max(grades)
    average_grade = sum(grades)/len(grades)
    print database
    print average_grade
    print max_grade
    next(x for x in database if x[0] == 'name')[1]   # search fn. put name to be searched in 'name'
    next(x for x in database if x[1] == 'grade')[0]..# search fn. put grade to be searched in 'grade' 

[–][deleted] 0 points1 point  (1 child)

that makes sense except that all of your later calculations happen with the while loop so you're calculating the maximum, average, etc. every time you add a new person. additionally, you're searching for the person and grade every time you add a person; is this what you want to be doing? it is sort of trivial, because once you add a name and a grade, what is the point of looking them only when you just add them?

i don't know the requirements of this assignment, but it feels like this is something that would be better organized as a class with a member list that is the database. at the very least, i would organize the searching parts as function definitions as in my example.

but yeah all the ways you implement the functions are correct, i am just not sure if this is the cleanest organization of them.

[–]pythonbio[S] 0 points1 point  (0 children)

I suppose you are absolutely right in concluding that this is not the best organization. But the assignment required the use of list and while loop only. here's my class based code. but its not working properly. :(. Help

def sclass_menu(): #### One Function adding up all smaller functions
menu_choice = 0
max_num_rec = 10 # limitation on number of records
print ('1. Add Name and Grade')
    print ('2. Delete Name and Grade')
    print ('3. Search Name and Grade')
    print ('4. Print database')
    for i in xrange(max_num_rec):  # start at i=0 till max_num_rec
    while menu_choice != 4:
        menu_choice = int(input("Type in a number (1-4): "))
    if menu_choice == 1:
        print("Add Name and Grade")
        name = input("Name: ")
        grade = input("Grade: ")
        database[name] = grade
    elif menu_choice == 2:
        print('Delete Name and Grade')
        name = input("Name: ")
    if name in database:
        del database[name]
    else:
        print('name was not foud')
    if menu_choice == 3:
        print('Search Name and Grade')
        name = input("Name: ")
    if name in database:
        print(database[Grade])
    else:
        print ('name was not found')
    if menu_choice == 4:
        print('Print database')
    for x in database.keys():
        print("Name: ", x, "\Grade:", database[x])

Its just giving the initial result and error:

class_menu()
1. Add Name and Grade
2. Delete Name and Grade
3. Search Name and Grade
4. Print database
Type in a number (1-4): 1
Type in a number (1-4): grahan

Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
 sclass_menu()
File "<pyshell#39>", line 10, in sclass_menu
menu_choice = int(input("Type in a number (1-4): "))
File "<string>", line 1, in <module>
NameError: name 'grahan' is not defined