I1 · Python Programming for AI

Project: A Marks Analyser

This project reads a CSV file of marks, computes summary statistics such as the average, highest, lowest and pass rate for each subject and each learner, and prints a clear report, combining files, dictionaries, loops, functions and formatting.

20 min Intermediate · Sublevel Beginner Jump to the activity

What you need: The earlier topics of this module.

Definition

Who scored highest, and what was the average? Can your program tell you in a second?

This project reads a CSV file of marks, computes summary statistics such as the average, highest, lowest and pass rate for each subject and each learner, and prints a clear report, combining files, dictionaries, loops, functions and formatting.

In simple words

First the program writes a small marks file, so it runs anywhere. Then it reads the file, turns the text into numbers, and works out the numbers a teacher or coach would want to see. This is exactly what the first step of a data science project looks like.

Overview

  • The marks analyser reads students' marks, computes statistics and prints a report.
  • It combines file reading, lists or dictionaries, loops, functions and formatted output.
  • Each step should be a small, tested function: load, validate, analyse, report.
  • Validation catches impossible values such as negative marks or marks above the maximum.
  • The same workflow, load, clean, analyse and report, is used in every data project.
  • Results must be presented fairly and kept private, because marks are personal data.

Why it matters

Reading data, cleaning it and summarising it is the core of data analysis and the first stage of every machine learning project. In the next module you'll do the same with pandas, in a few lines.

Key terms

Summary statistics
Numbers that describe a data set, such as mean, highest, lowest and pass rate.
Pass rate
The percentage of results at or above the pass mark.
Data validation
Checking each value is present and sensible before using it.
Aggregation
Combining many values into one, by learner or by subject.
Report
Formatted output that presents results clearly.
Separation of concerns
Keeping reading, calculating and printing in separate functions.

Types

A marks report can contain several types of analysis. Each answers a different question for teachers and students.

1. Summary statistics

Single numbers that describe the whole set of marks: mean, median, highest, lowest and range.

  • How it works: Use sum()/len() for the mean, sorted() for the median, max() and min() for extremes, and the statistics module for standard deviation.
  • Example: Maths: mean 71.4, median 74, highest 98, lowest 31.
  • When to use it: Use it as the first view of any marks data; report the median too when a few very low marks pull the mean down.

2. Grading and ranking

Turning marks into grades with rules, and ordering students by total.

  • How it works: An if-elif ladder maps percentages to grades; sorted(..., key=..., reverse=True) with enumerate() assigns ranks.
  • Example: 91% becomes A1 under a nine-point grading scale; the top three are listed with their ranks.
  • When to use it: Use it for report cards; handle ties so that equal totals get equal ranks.

3. Distribution analysis

Counting how many students fall into each band of marks.

  • How it works: Group marks into bands (0–32, 33–49, 50–74, 75–100) with a dictionary or Counter, then print counts or draw a histogram.
  • Example: 4 students below 33, 10 between 33 and 49, 18 between 50 and 74, 8 at 75 or above.
  • When to use it: Use it to see the shape of results: whether most students cluster in the middle or split into high and low groups.

4. Comparison across subjects or groups

Comparing averages and pass rates between subjects, sections or terms.

  • How it works: Compute the same statistic for each group with a loop over a dictionary of lists, then show a side-by-side table.
  • Example: Science average 68 versus Maths 72; Section B's pass rate rose from 81% to 90% between terms.
  • When to use it: Use it to find where teaching or extra support is most needed.

5. Finding students who need support

Flagging individual students with low marks, falling marks or unusual results.

  • How it works: Apply rules such as "below 40 in any subject" or "dropped more than 15 marks since last term", and list the matches privately.
  • Example: Ravi's science marks fell from 72 to 51, so he is flagged for a teacher's attention.
  • When to use it: Use it to help students early; share such lists only with teachers, never publicly.

Explained in detail

What the project does

The marks analyser reads a CSV file in which each row is a learner and each column after the name is a subject. It then answers practical questions a teacher would ask: what is each learner's total and average, what is each subject's average, highest and lowest mark, how many passed in each subject, and who are the top three overall? It is a small but complete data pipeline, read, clean, compute and report, the same shape as real analytics and machine-learning projects, only smaller.

Structure it in functions

FunctionInputOutput
load_marks(path)File pathDictionary: name → {subject: mark}
clean(records)Raw recordsValid numbers only, with a list of problems found
learner_summary(records)Clean recordsTotal and average per learner
subject_summary(records)Clean recordsAverage, highest, lowest and pass rate per subject
print_report(...)The summariesA neatly aligned report

Keeping these separate means you can test each function with a tiny example, swap the CSV for another file without touching the calculations, or later replace print_report with a chart. This separation of concerns is how professional data code is organised.

Real data is messy

  • A mark may be blank, "AB" for absent, or a typing slip such as 7O instead of 70; decide a rule and record each problem.
  • Values above 100 or below 0 are errors, not achievements.
  • Names may have extra spaces or inconsistent capitals; strip and normalise them.
  • An absent learner should not be counted as scoring zero in a subject average, unless the school's rule says so.

Reading the results critically

A report is only useful if it is read wisely. An average hides spread, so add the range or show the lowest and highest. A subject with a low pass rate might need more teaching time, or might simply have had a harder paper. Comparing groups of different sizes can mislead. These are the data-literacy habits from the Beginner level, now applied with your own code. Finally, treat marks as personal data: keep the file private, and never share learner-level results publicly.

How it works

  1. Read the CSV into a list of rows.
  2. Convert marks from text to numbers.
  3. For each subject: average, highest and lowest.
  4. For each learner: total and average; find the topper.
  5. Count how many passed every subject (40 or more).
  6. Print a neatly formatted report.

In code

The whole analyser: write a sample file, read it, compute statistics and print a report.

marks_analyser.py
import csv
from statistics import mean

rows = [["name", "maths", "science", "english"],
        ["Aarav", 72, 65, 80], ["Meera", 91, 88, 85], ["Kabir", 38, 55, 60],
        ["Sana", 85, 79, 92], ["Ishaan", 64, 35, 70]]
with open("marks.csv", "w", newline="") as f:
    csv.writer(f).writerows(rows)

with open("marks.csv") as f:
    records = list(csv.DictReader(f))
subjects = ["maths", "science", "english"]
for record in records:
    for subject in subjects:
        record[subject] = int(record[subject])

print("Subject report")
for subject in subjects:
    scores = [r[subject] for r in records]
    print(f"  {subject:<8} average {mean(scores):5.1f}  high {max(scores)}  low {min(scores)}")

def average(record):
    return mean(record[s] for s in subjects)

topper = max(records, key=average)
print(f"Topper: {topper['name']} with an average of {average(topper):.1f}")
passed_all = [r["name"] for r in records if all(r[s] >= 40 for s in subjects)]
print(f"Passed every subject: {len(passed_all)} of {len(records)} -> {passed_all}")

Output

Subject report
  maths    average  70.0  high 91  low 38
  science  average  64.4  high 88  low 35
  english  average  77.4  high 92  low 60
Topper: Meera with an average of 88.0
Passed every subject: 3 of 5 -> ['Aarav', 'Meera', 'Sana']

Try it yourself

Project checklist

Work through these in the runner above, then extend the analyser.

  1. Run it and check one subject's average by hand.
  2. Add a sixth learner to the rows and run again.
  3. Print each learner's grade using the grade() function from the conditions topic.
  4. Find the subject with the lowest average and print it.

Think about it

  • Which step took the most lines of code? In pandas, the same work takes about five lines.

Common mistakes

  • Forgetting to convert marks from text, so max('9', '10') gives '9'.
  • Hard-coding the number of learners instead of using len().
  • Printing a report so messy that nobody can read it. Format with f-strings.

Check yourself

Question 1

1. Why convert the marks with int()?

Question 2

2. What does all(r[s] >= 40 for s in subjects) check?

Question 3

3. max(records, key=average) finds…

Summary

  • Read the CSV, convert text to numbers, then summarise.
  • Averages, highs, lows and pass rates tell the story of the data.
  • This is the first stage of every data and ML project.

Finished reading?

Sources: Python documentation, reading CSV records