ADVERTISEMENT
ADVERTISEMENT

Arrays of Objects Example in Python

Here, we are going to learn about the array of objects in Python and going to explain it by writing Python program to take student information and store it into an array of objects and then print the result.
Submitted by Shivang Yadav, on February 15, 2021

Python objects are the instances of class in Python. And storing multiple objects into an array is an array of objects.

Problem Statement: We need to store details of multiple students in an array of objects. And then print the students' results.

Problem Description: We will take the students' details, (roll number, name, marks in physics, chemistry and maths) from users for multiple students as required by users. And the print the result that displays student's roll number, name and percentage ( sum of all marks  / 300 * 100).

Algorithm:

  • Step 1: Create a class named Student to store student information.
  • Step 2: Take inputs from the user, and store it into an array of objects using getStudentInfo() method.
  • Step 3: After the user has entered all student's information. Print the result.
  • Step 4: The result printed as roll number, name, and percentage using printResult() method.

Program to illustrate arrays of Objects in Python

class Student:
    def GetStudentInfo(self):
        self.__rollno = input("Enter Roll Number ")
        self.__name = input("Enter Name ")
        self.__physics = int(input("Enter Physics Marks "))
        self.__chemistry = int(input("Enter Chemistry Marks "))
        self.__maths = int(input("Enter Math Marks "))
    def printResult(self):
        print(self.__rollno,self.__name, ((int)( (self.__physics+self.__chemistry+self.__maths)/300*100 )))

StudentArray = []

while(True):
    student = Student()
    student.GetStudentInfo()
    StudentArray.append(student)
    ch = input("Add More y/n?")
    if(ch=='n'):break

print("Results : ")

for student in StudentArray:
    student.printResult()

Output:

Enter Roll Number 001
Enter Name John
Enter Physics Marks 87
Enter Chemistry Marks 67
Enter Math Marks 90
Add More y/n?y
Enter Roll Number 002
Enter Name Jane
Enter Physics Marks 54
Enter Chemistry Marks 87
Enter Math Marks 98
Add More y/n?n
Results : 
001 John 81
002 Jane 79

Python class & object programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.