Write a python program to Searching of objects from an array of objects using ID


The program defines a Student class, creates a list of Student objects, and allows you to search for a student by their ID. Here's a breakdown of the code:

  • class Student: This class represents a student with attributes such as student_id, name, and per (percentage).
  • __init__(self, student_id, name, per): The constructor initializes a Student object with the provided student_id, name, and per.
  • __str__(self): This special method returns a string representation of the Student object, displaying the student's ID, name, and percentage.
  • An array (list) of Student objects is created and initialized with student data.
  • search_student_by_id(student_id): This function searches for a student by their ID. It iterates through the students list and returns the first matching student object with the specified student_id, or None if no match is found.
  • The code prints all student IDs in the list using a for loop.
  • The user is prompted to enter a student ID to search for.
  • The search_student_by_id function is called with the user-provided ID, and if a student with that ID is found, it's printed along with a "Student Found" message. If no matching student is found, a "Student Not Found" message is displayed.

Source Code

class Student:
    def __init__(self, student_id, name, per):
        self.student_id = student_id
        self.name = name
        self.per = per
 
    def __str__(self):
        return "Student ID : " + str(self.student_id) + "\nStudent Name : " + self.name + "\nPercentage : " + str(self.per)
 
# Create an array (list) of Student objects
students = [
	    Student(101, "Mithra", 85.5),
	    Student(102, "Akhil", 78.0),
	    Student(103, "Tiya", 92.5),
	    Student(104, "Ramesh", 84.5),
	    Student(105, "Sam Kumar", 65.5)
	   ]
 
def search_student_by_id(student_id):	# search for a student by ID
    for student in students:
        if student.student_id == student_id:
            return student
    return None
 
# Print all student IDs
print("*** Student IDs ***")
for student in students:
    print(student.student_id)
 
search_id = int(input("\nEnter Student ID to Search : "))
 
found_student = search_student_by_id(search_id) # Search for the student by ID
 
if found_student:
    print("Student Found")
    print(found_student)
else:
    print("Student Not Found")

Output

*** Student IDs ***
101
102
103
104
105

Enter Student ID to Search : 103
Student Found
Student ID : 103
Student Name : Tiya
Percentage : 92.5

Example Programs