Build a school timetable with python

Today, we’ll learn how with a simple script, we can create a program which helps us to build a school timetable.

We suppose that as a school manager, we want to make easy the way to establish a school timetable for each class.

Application process


How the program will work. That is what we’ll see here.

  • You enter all class subjects, separate them by comma
  • for each school hour, you choose what subject class will have
  • In the end, it will save the planning into a CSV file


  • You must specify seven subjects at least
  • A subject can’t have more than 6 hours/week
  • School days are Monday to Friday



In order to write this script, you must be familiar with some things:

  • csv module
  • pathlib module (but you can use os module instead)
  • functions, lists, dictionaries, loop, etc.

Well, now, it’s time to code.


Our script will be written in a file called, so create a folder called school_timetable and inside it, create our file.

Firstly, begin by import modules and define the variables we need.

import pathlib
import csv

# Let's start by defines variables
subjects_list = []
start_hour = 8 # school start at
next_hour = 9 # 1rst next hour is
school_days = [
time_slot_list = [] # get list of time slot
subject_per_slot = {}

In your opinion, is that all? Have we defined all the necessary variables? Remember that we must ensure that each subject cannot exceed 6 hours! To realize it, we will use a dictionary in which the key will be the material and value the maximum value (an hour) for each of the subjects. This value will decrease each time the subject concerned is used in the timetable.

MAX_HOUR_PER_SUBJECT = 6 # use capital letter because it's a constant variable
subject_hour_count = {}

We know that in programming, we’ve never one solution (method) to do something. So, in order to fill in subjects list, I want to present you two methods and you’ll be free to use one of them or your own method.

1rst method

def fill_in_subjects_list():
    """Ask user subjects and fill in subjects list"""

    enter_another_subject = True
    while enter_another_subject:
        subject = input('Type another subject: ')
        subject = subject.capitalize()

        if not subject in subjects_list:
            subject_hour_count[subject] = MAX_HOUR_PER_SUBJECT
            print(f'You\'ve already type {subject} in list.')

        question = input('Enter another subject (type "n" to exit)?')

        if question.lower() == 'n':
            enter_another_subject = False

2nd method

def fill_out_subjects_list():
    """Ask user subjects and fill in subjects list"""

    subjects = input('Type all subjects you want add in subjects list\
and separate them by comma: ') # we collect all subjects

    the_subjects = subjects.replace(', ', ',') # remove space after comma

    # Split all subjects in order to put them into a list
    the_subjects = the_subjects.split(',')

    for subject in the_subjects:
        subject = subject.capitalize()

        if not subject in subjects_list:
            subject_hour_count[subject] = MAX_HOUR_PER_SUBJECT

Choose one of two methods, not both at time.

We’ve to define two methods:

  • one to ask user subject he wants to add
  • one to add subject chosen in the timetable
def ask_hour():
    """Ask hour to user"""
    print(f'Subjects list: {subjects_list}')

    print(f'Planning time: {start_hour}h-{next_hour}h')
    user_answer = input('What\'s subject do you want put here? ')

    return user_answer

def fill_in_timetable():
    """Display an hour & ask user which subject he want to put there"""
    global start_hour
    global next_hour

    for day in school_days:
        # Reset start and next hour
        the_hour = {}
        time = 0
        start_hour = 8 # we suppose that school start at
        next_hour = 9

        print(f'{day.capitalize()} timetable')

        while time < 4: # Suppose we've 4hours course/day (you can change it)

            hour_format = f'{start_hour}h-{next_hour}h' # format time slot
            # it's represent 8 hours/per day for school
            if time == 2: # if it's a midday (, make a break
                # Add a break in timetable with 'Break time' as inscription
                subject_per_slot[hour_format] = ['Break time']

                # Add hour format while making sure we avoid duplicate
                if not hour_format in time_slot_list:

                chosen_subject = ask_hour().capitalize()
                print(f'start_hour: {start_hour}')
                print(f'next_hour: {next_hour}')

                # Check that subject chosen by user is in subjects list
                while not chosen_subject in subjects_list:
                    print(f'{chosen_subject} is not in subjects list.')
                    print('Choose another subject.')
                    chosen_subject = ask_hour().capitalize()

                # Add hour format while making sure we avoid duplicate
                if not hour_format in time_slot_list:
                    subject_per_slot[hour_format] = [chosen_subject]
                    subject_per_slot[hour_format] += [chosen_subject]

                # Check that chosen subject max hours didn't reached
                for subject, max_hour in subject_hour_count.items():
                    if chosen_subject == subject:
                        # remove one hour on subject max hour
                        subject_hour_count[chosen_subject] = max_hour - 1

            # go to next hour
            start_hour += 1
            next_hour += 1
            time += 1


Well done. Now we can add a scenario to our script.

print(f'Subject per slot: {subject_per_slot}')

timetable_path = pathlib.Path.cwd() / 'timetable.csv'

# Now, let's write process to save timetable into a csv file
with open(timetable_path, 'w') as timetable_file:
    timetable_writing = csv.writer(timetable_file)

    # Write headers into csv file
    csv_headers = ['Hours']

    # Write content into csv file
    for time_slot, concerned_subjects in subject_per_slot.items():
        time_line = [time_slot]
        concerned_subjects_list = []

        if concerned_subjects == ['Break time']:
            for x in range(0, len(school_days)):
                concerned_subjects_list.append('Break time')
            concerned_subjects_list = concerned_subjects

        final_line = time_line + concerned_subjects_list
    print('Your timetable is ready')


That’s all! Now, we can open csv file with any spreadsheet software (LibreOffice, Excel, etc.)