run at pycharm community
PYTHON CREATING CLASS AND ATTRIBUTE :
1. Create a Class and initialize attribute of the following:
Class name: Student
Attribute: First Name
Last Name
Sex
Age
2. From the created class, create 5 objects, and display it using pretty table.
SOLUTION CODE
from prettytable import PrettyTable
class Student:
def __init__(self,First_Name,Last_Name,Sex,Age):
self.First_Name = First_Name
self.Last_Name = Last_Name
self.Sex = Sex
self.Age = Age
#create the five objcets
object1 = Student("Kelly","Daniel","Male",31)
object2 = Student("Stella","Eve","Female",22)
object3 = Student("Stephen","Fred","Male",28)
object4 = Student("John","Muthama","Male",36)
object5 = Student("Eunice","Brenda","Fale",19)
print(object1.First_Name)
print(object1.Last_Name)
# Creating a new table
stuentTable = PrettyTable(["First Name", "Last Name", "Sex", "Age"])
# Add rows
stuentTable.add_row([object1.First_Name, object1.Last_Name, object1.Sex,object1.Age])
stuentTable.add_row([object2.First_Name, object2.Last_Name, object2.Sex,object2.Age])
stuentTable.add_row([object3.First_Name, object3.Last_Name, object3.Sex,object3.Age])
stuentTable.add_row([object4.First_Name, object4.Last_Name, object4.Sex,object4.Age])
stuentTable.add_row([object5.First_Name, object5.Last_Name, object5.Sex,object5.Age])
#print the details using the pretty table
print(stuentTable)
Comments
Leave a comment