Skip to content
Python project #17Intermediate

Attendance Tracker

Turn daily attendance registers into percentages, shortage warnings, longest absence streaks, daily rates and the classes needed to recover.

Estimated time
~3 hours to build
Files
4 files · 261 lines
Technologies
Python 3, dataclasses, datetime.date

Introduction

Colleges often require 75% attendance. This tracker reads a simple register, handles holidays, late marks and medical leave, and tells each student exactly where they stand — including how many classes they must attend to recover.

Problem statement

Read a first line listing students, then one line per day with an ISO date and one mark per student (P present, A absent, L late, M medical leave) or the word holiday. Skip lines with bad dates, duplicate dates or the wrong number of marks, reporting why. For each student show classes attended out of classes counted, the percentage, the longest absence streak and a status: ok, warning (below 80%) or shortage (below 75%) with the number of consecutive classes needed to reach 75%. Show each day's attendance rate and the lowest day.

Objectives

  • Parse a custom text format robustly
  • Compute statistics with properties
  • Find streaks with a single pass
  • Solve a 'how many more' question with a loop

Features

  • P, A, L and M marks plus holidays
  • Validation with skipped-line reasons
  • Percentages, warnings and shortages
  • Longest absence streak
  • Daily attendance chart

Concepts demonstrated

  • Parsing
  • Properties
  • Streak detection
  • Simple simulation

System architecture

Student stores its marks and computes counted, attended and percentage as properties; medical leave is excluded from the count. longest_absence scans marks keeping the current and best run. classes_needed adds hypothetical attended classes until the percentage reaches 75. parse builds students and daily rates while collecting problems instead of stopping.

Folder structure

TextProject tree
attendance-tracker/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

114 lines
Pythonmain.py
"""Attendance Tracker: daily attendance registers turned into percentages, warnings and trends.
Input (standard input):
students: 101 Asha, 102 Ravi, 103 Meera first line
2026-11-02 P A P one line per day, one mark per student
2026-11-03 holiday days that don't count
Marks: P present, A absent, L late (counts as present), M medical leave (excluded from the total).
"""
import sys
from dataclasses import dataclass, field
from datetime import date
REQUIRED, WARNING = 75, 80
@dataclass
class Student:
roll: str
name: str
marks: list[str] = field(default_factory=list)
@property
def counted(self) -> int:
return sum(1 for m in self.marks if m != "M")
@property
def attended(self) -> int:
return sum(1 for m in self.marks if m in "PL")
@property
def percentage(self) -> float:
return 100 * self.attended / self.counted if self.counted else 100.0
def longest_absence(self) -> int:
best = run = 0
for m in self.marks:
run = run + 1 if m == "A" else 0 if m in "PL" else run
best = max(best, run)
return best
def classes_needed(self) -> int:
"""Consecutive classes to attend to reach the required percentage."""
needed = 0
while 100 * (self.attended + needed) / (self.counted + needed) < REQUIRED:
needed += 1
return needed
def parse(lines: list[str]) -> tuple[list[Student], list[tuple[date, float]], int, list[str]]:
header = lines[0]
if not header.lower().startswith("students:"):
raise SystemExit("The first line must start with 'students:'")
students = []
for entry in header.split(":", 1)[1].split(","):
roll, _, name = entry.strip().partition(" ")
students.append(Student(roll, name))
days, holidays, problems = [], 0, []
seen: set[date] = set()
for number, line in enumerate(lines[1:], start=2):
parts = line.split()
try:
day = date.fromisoformat(parts[0])
except ValueError:
problems.append(f"line {number}: '{parts[0]}' is not a date")
continue
if day in seen:
problems.append(f"line {number}: {day} recorded twice, ignored")
continue
seen.add(day)
if len(parts) == 2 and parts[1].lower() == "holiday":
holidays += 1
continue
marks = [m.upper() for m in parts[1:]]
if len(marks) != len(students) or any(m not in "PALM" for m in marks):
problems.append(f"line {number}: expected {len(students)} marks from P/A/L/M")
continue
for student, mark in zip(students, marks):
student.marks.append(mark)
present = sum(m in "PL" for m in marks)
counted = sum(m != "M" for m in marks)
days.append((day, 100 * present / counted if counted else 100.0))
return students, days, holidays, problems
def main() -> None:
lines = [l.strip() for l in sys.stdin if l.strip()]
if not lines:
print("No input.")
return
students, days, holidays, problems = parse(lines)
for p in problems:
print(f"Skipped {p}")
print(f"\n{len(days)} working days recorded, {holidays} holiday(s).\n")
print(f"{'Roll':<6}{'Name':<8}{'Present':>8}{'Of':>4}{'%':>8} {'Longest absence':<16}Status")
for s in students:
if s.percentage < REQUIRED:
status = f"SHORTAGE - attend next {s.classes_needed()} classes"
elif s.percentage < WARNING:
status = "warning"
else:
status = "ok"
streak = f"{s.longest_absence()} day(s)"
print(f"{s.roll:<6}{s.name:<8}{s.attended:>8}{s.counted:>4}{s.percentage:>7.1f}% {streak:<16}{status}")
print("\nDaily attendance")
for day, rate in days:
print(f" {day:%a %d %b} {rate:5.1f}% {'#' * round(rate / 10)}")
low = min(days, key=lambda d: d[1])
print(f"\nLowest attendance: {low[0]:%A %d %B} ({low[1]:.1f}%)")
print(f"Class average: {sum(s.percentage for s in students) / len(students):.1f}%")
if __name__ == "__main__":
main()

What each file does

main.py
The Student class, the register parser and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Skipped line 10: expected 4 marks from P/A/L/M
Skipped line 11: 2026-11-12 recorded twice, ignored
Skipped line 12: '11-13-2026' is not a date
Skipped line 13: expected 4 marks from P/A/L/M
9 working days recorded, 1 holiday(s).
Roll Name Present Of % Longest absence Status
101 Asha 8 9 88.9% 1 day(s) ok
102 Ravi 3 9 33.3% 3 day(s) SHORTAGE - attend next 15 classes
103 Meera 8 8 100.0% 0 day(s) ok
104 Kiran 6 9 66.7% 1 day(s) SHORTAGE - attend next 3 classes
Daily attendance
Mon 02 Nov 75.0% ########
Tue 03 Nov 75.0% ########
Wed 04 Nov 50.0% #####
Fri 06 Nov 100.0% ##########
Mon 09 Nov 75.0% ########
Tue 10 Nov 75.0% ########
Wed 11 Nov 50.0% #####
Mon 16 Nov 75.0% ########
Tue 17 Nov 75.0% ########
Lowest attendance: Wednesday 04 November (50.0%)
Class average: 72.2%
Input
students: 101 Asha, 102 Ravi, 103 Meera, 104 Kiran
2026-11-02 P A P P
2026-11-03 P A L P
2026-11-04 P A P A
2026-11-05 holiday
2026-11-06 P P M P
2026-11-09 P A P P
2026-11-10 A P P P
2026-11-11 P A P A
2026-11-12 P P P X
2026-11-12 P P P P
11-13-2026 P P P P
2026-11-13 P P P
2026-11-16 P A P P
2026-11-17 P P P A

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • Four lines are skipped: an invalid mark X, a repeated date, a date in the wrong format and a line with three marks.
  • Ravi attended 3 of 9 classes (33.3%) and must attend the next 15 to reach 75%.
  • Meera's medical leave doesn't count against her, so she is at 100%.

Common errors

Medical leave lowers the percentage

Exclude M marks from the number of classes counted.

A repeated date is counted twice

Keep a set of seen dates and skip repeats, as parse() does.

Possible improvements

  • Read registers from CSV exported by a spreadsheet
  • Report attendance per week
  • Produce a printable list of shortage students

Additional challenges

  1. 1Show each student's attendance trend (improving or declining).
  2. 2Allow per-subject registers and combine them.
  3. 3Predict the final percentage if the current pattern continues.

Built and tested it yourself? Mark it to update your dashboard.