coach22
coach22

Reputation: 5

Python - How to search for an object stored in a list, by looking up an attribute of the object

I have a class which stores student attributes:

class Student(object):
    def __init__(self):
        self.__name = ''
        self.__nationality= ''
        self.__age = 0
        self.studentId=''

class EnglishStudent(Student):
    def __init__(self):
        Student.__init__(self)
        self.__englishStudents = []   

I import the student details from a csv. and create new student objects from them and store them in self.__englishStudents[].

I am trying to create a function that takes student id as input, checks if the student id is in self.__englishStudents[] and returns all the student details if they are found.

Any tips?

This is what i have so far but it does not seem to find the studentID even though I am certain it is in self.__englishStudents[]

def getStudentDetails(self, studentId):
        for student in self.__englishStudents:
            if self.studentId == studentId
                print(student.getName(), student.getAge())
            else:
                print("Student ID not found") 
                break               

Upvotes: 0

Views: 163

Answers (1)

Potato
Potato

Reputation: 51

It looks like you're trying to check self.studentId instead of the student object that you're comparing for. Try changing if self.studentId == studentId to if student.studentId == studentId

Block would become:

def getStudentDetails(self, studentId):
        for student in self.__englishStudents:
            if student.studentId == studentId
                print(student.getName(), student.getAge())
            else:
                print("Student Id not found") 
                break

Upvotes: 1

Related Questions