Assuming s.subjects is None or some other False value when there are no subjects, and likewise for books
for s in students:
    for subject in s.subjects or []:
        for book in subject.books or []:
            writer.writerow(s.name, s.class, subject.name, book.name)
More generally, you can write
for s in students:
    for subject in s.subjects if <condition> else []:
        for book in subject.books if <condition> else []:
            writer.writerow(s.name, s.class, subject.name, book.name) 
Where <condition> is whatever expression makes sense
5
solved How can I make the efficent for loop in Python?