Editor

Sort Students by GPA

Intermediate · Write the code · from Python Dataclasses: Less Boilerplate, More Readable Code

From the lesson: Python Dataclasses: Less Boilerplate, More Readable Code

Imagine filling out a form where you have to write your name, address, and phone number. Now imagine filling out 50 forms where every single one asks for the same information in a slightly different format. That's what writing Python classes feels like sometimes.

Read the lesson

Create a dataclass Student with order=True and two fields: gpa (float) and name (str). Note: put gpa first so sorting uses GPA as the primary key. Create three students: (3.5, 'Charlie'), (3.9, 'Alice'), (3.2, 'Bob'). Sort them and print each student's name and GPA.

from dataclasses import dataclass
# Create Student with order=True

More Dataclass exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz