Sikau

Python · Day 5 · about 40 min

Project: A gradebook

Parse scores, grade them and print a ranked report.

Exam results day

A teacher in Pokhara exports the class's marks from a spreadsheet as lines of text: "Asha, 82", "Bikash,91", a stray blank line, inconsistent spaces. She needs letter grades, a class average and a ranked list to pin on the notice board. That's a classic small Python job — and it uses everything from this unit.

You'll build it as four small functions, each easy to test on its own: one to parse, one to grade, one to average, one to report. Splitting a job like this is how real programs stay understandable.

Parse, then compute

Real input is messy, so parsing comes first and is defensive: skip blank lines (if not line.strip(): continue), split each line on the comma, strip spaces from the name and convert the score with int() — which happily ignores surrounding spaces, so int(" 91 ") is 91. Unpacking name, score = line.split(",") also checks there are exactly two parts.

Grading is a chain of if/elif checks from the highest band down, so the first match wins. The average is sum(scores.values()) / len(scores) — but guard the empty class, or you'll divide by zero. round(x, 1) rounds to one decimal place.

def grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    return "F"

print(grade(95), grade(85), grade(10))

The rest of this lesson

  • Sorting with a keyexplain
  • Tuples compare in orderpredict
  • The program's pipelineorder
  • Which tool for which job?match
  • Build the gradebookchallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 10 lessons of Python