How to Document a Python Data Analysis Script So a Marker Can Follow Your Logic

How to document a Python data analysis script cover image
Python Guide

A working Python script is not the same as an understandable one. When a marker opens your code, they need to see what you were trying to find out, why you made each decision and how your results were produced.

This guide shows how to document a Python data analysis script step by step, with examples you can copy into your own dissertation or assignment.

By the Analytivio team9 min readUpdated November 2026

The short answer

Start with a clear research objective, split the script into numbered sections, write comments that explain decisions rather than obvious code, explain why each statistical test was chosen, and use meaningful names and docstrings for any functions.

1. Start with the research objective

Do not begin with dozens of lines of code without explaining the purpose.

# Objective:
# Examine the relationship between study hours
# and students' academic performance.

This immediately gives the marker context. A slightly fuller header is even better:

"""
Project : Study habits and exam performance (MSc dissertation)
Author  : Student ID 1234567
Data    : data/raw/survey_2026.csv (n = 214)
Purpose : Test whether weekly study hours predict exam scores,
          controlling for prior attainment.
Python  : 3.11 (packages in requirements.txt)
"""

2. Divide your analysis into sections

A long script becomes much easier to follow when it has a logical structure:

  1. Import libraries
  2. Load dataset
  3. Data cleaning
  4. Descriptive statistics
  5. Exploratory analysis
  6. Statistical testing
  7. Model development
  8. Model evaluation
  9. Visualisation

This is particularly helpful when your analysis contains several stages. Use clear section headers so the marker can jump straight to what they want to check:

# ============================================
# 3. DATA CLEANING
# ============================================

3. Comment on decisions, not obvious code

Avoid comments such as:

df = pd.read_csv("data.csv")  # Load data

Instead, explain an analytical decision:

# Remove records with missing values in variables
# required for the regression analysis.
df = df.dropna(subset=["age", "income"])

The goal is to help the marker understand your reasoning, not translate every line of Python.

4. Explain your statistical tests

If you perform correlation, regression, ANOVA or another statistical test, explain why you selected it. This connects your code with your research methodology.

# H1: Study hours predict exam score after controlling for prior grade.
# Multiple regression chosen because the outcome is continuous
# and we need to control for a covariate.
model = smf.ols("exam_score ~ study_hours + prior_grade", data=df).fit()

# Assumption check: residuals vs fitted values (see Figure 3).

Linking each test to a hypothesis number from your methodology chapter makes it very easy for a marker to cross-check.

5. My experience with Python

When I first started working with Python, my priority was simply getting the code to run. As my projects became more complex, particularly with data cleaning, statistical analysis, machine learning, prediction and model evaluation, I realised that working code is not necessarily understandable code.

Clear sections and meaningful comments made it much easier to return to my own analysis and understand what I had done.

6. Use meaningful variable names

UnclearClear
df2survey_clean
xstudy_hours
m1model_hours_only
resttest_gender_stress

Good names reduce the number of comments you need, because the code explains itself.

7. Write docstrings for functions

If you repeat a step, such as creating a scale score, put it in a function and describe what it does, its inputs and its output:

def scale_mean(data, items, reverse=None, max_score=5):
    """Return the mean score for a questionnaire scale.

    data      : DataFrame containing the item columns
    items     : list of item column names
    reverse   : items to reverse-score before averaging
    max_score : highest response option (used for reversing)
    """
    scored = data[items].copy()
    for item in (reverse or []):
        scored[item] = (max_score + 1) - scored[item]
    return scored.mean(axis=1)

8. Show your results, not just your code

Print or save the key results with labels so the marker can match them to your results chapter. Saving tables and figures with clear file names, such as table2_regression.csv or figure3_residuals.png, makes the link between code and dissertation obvious.

summary_table = model.summary2().tables[1].round(3)
summary_table.to_csv("outputs/table2_regression.csv")
print("Table 2: Regression predicting exam score")
print(summary_table)

Notebook or script?

Jupyter notebooks are excellent for documentation because you can mix headings, explanations, code and output. Use Markdown cells for each section heading and a short explanation of the decision being made. Before submitting, restart the kernel and run all cells so the output matches the code. Plain .py scripts are better for long pipelines; in that case a short README explains the order in which to run them.

Documentation checklist before you submit

  • A header states the objective, data source and Python version.
  • The script is split into numbered sections.
  • Comments explain decisions, exclusions and assumptions.
  • Each statistical test is linked to a hypothesis or research question.
  • Variable and function names are meaningful.
  • Outputs are labelled to match tables and figures in your dissertation.
  • The code runs from start to finish without errors.

A well-documented script template

"""Study habits and exam performance: main analysis."""

# ============ 1. IMPORT LIBRARIES ============
import pandas as pd
import pingouin as pg
import statsmodels.formula.api as smf

# ============ 2. LOAD DATA ============
# Raw survey export, never edited by hand.
df = pd.read_csv("data/raw/survey_2026.csv")

# ============ 3. DATA CLEANING ============
# Exclude incomplete responses (n = 9) because they
# lack the outcome variable.
df = df.dropna(subset=["exam_score"])

# ============ 4. DESCRIPTIVE STATISTICS ============
print(df[["study_hours", "exam_score"]].describe().round(2))

# ============ 5. HYPOTHESIS TESTING ============
# H1: study hours correlate positively with exam score.
print(pg.corr(df["study_hours"], df["exam_score"]))

The exclusion count in the comment is an example. Replace it with the real figure from your own data.

Common documentation mistakes

  • Leaving old, commented-out code that no longer runs.
  • Writing comments that no longer match the code after changes.
  • Using comments like “fix this later” in the submitted version.
  • Explaining what the code does but never why the decision was made.
  • Submitting a notebook with cells that were run out of order.

How markers typically review code

Markers usually skim the structure first, then check a few key steps: how the data were cleaned, which tests were run and whether the output matches the results chapter. Make those three things easy to find. A clear header, numbered sections and labelled outputs mean a marker can confirm your analysis in minutes rather than searching through hundreds of lines.

Linking your code to your methods chapter

Your methods chapter and your code should tell the same story. Use the same variable names, hypothesis numbers and exclusion rules in both. If your methods chapter says that participants who failed an attention check were removed, the code should contain that rule with a comment pointing to it. Consistency between the two is one of the quickest ways to build a marker’s confidence in your work.

Tools that help keep code readable

Formatting tools can tidy your code automatically. Black formats Python code in a consistent style, and linters such as flake8 or Ruff highlight unused variables and possible errors. Running one of these before submission makes your script look professional and easier to read, and it often catches small mistakes you might otherwise miss.

pip install black ruff
black scripts/
ruff check scripts/

Comments vs. docstrings vs. README

TypeWhere it goesPurpose
Inline comment (#)Next to or above specific linesExplain a decision or non-obvious step
Docstring (“”” “””)Start of a file, function or classDescribe what it does, inputs and outputs
Markdown cellJupyter notebooksExplain a section in full sentences
READMEProject folderExplain how to run the whole analysis

Using each type for its proper purpose keeps your documentation organised: detailed reasoning in comments, function descriptions in docstrings and setup instructions in the README.

Documenting data cleaning decisions

Cleaning decisions affect results more than many students realise, so markers look at them closely. For each step, record what you did, how many cases it affected and why. A short printed log keeps this transparent:

n_before = len(df)
df = df[df["attention_check"] == 1]
print(f"Removed {n_before - len(df)} participants who failed the attention check")

How Analytivio can help document your Python analysis

Analytivio is a data analytics consultancy supporting students, researchers and businesses with analysis they can trust and explain. For Python analysis scripts, we can help you:

  • Restructure and comment your script so markers can follow it.
  • Link your code clearly to your hypotheses and methodology.
  • Check that every reported result is produced by the code.
  • Prepare a README and appendix for submission.

We explain every step in plain language, so you understand your results and can defend them to a supervisor, examiner or client. Message us on WhatsApp for a free consultation, or explore our research and academic data help.

Writing comments for different readers

Remember that your code may be read by more than one person. A supervisor wants to see that your methods match your research design. An external examiner may only skim the structure. A future you, returning months later, needs enough detail to rerun the analysis without guesswork. Good documentation serves all three readers at once: a short summary at the top, clear section headings for navigation and specific comments where decisions were made. Writing with these readers in mind keeps your comments focused and useful rather than repetitive.

Frequently asked questions

How many comments should a Python analysis script have?

Enough to explain the purpose of each section and every important decision. You do not need a comment for every line.

Should I use a Jupyter notebook or a .py script for my dissertation?

Either can work. Notebooks are good for combining explanation and output, while scripts suit longer pipelines. Follow your department’s guidance.

What is a docstring in Python?

A docstring is a text description inside triple quotes at the start of a function, class or file that explains what it does, its inputs and outputs.

Do markers actually read my code?

Many markers check code to confirm how results were produced, especially for data-focused dissertations. Clear documentation makes that check quick and positive.

Should I explain why I removed data in my code?

Yes. Any exclusion or cleaning rule should be commented in the code and described in your methods section.

Should I include my Python code in the dissertation appendix?

Usually yes, unless your department says otherwise. Include the documented code or a link to a repository, plus instructions for running it.

How do I make my Python code easier to read?

Use meaningful names, consistent formatting, numbered sections and comments that explain decisions. Formatting tools such as Black help keep the style consistent.

Should comments be written in full sentences?

Short phrases are fine for simple notes, but use full sentences when explaining analytical decisions, so the reasoning is clear to any reader.

Want your Python script reviewed before submission?

Our analysts can review, restructure and document your code, check that it reproduces your results and explain every step in plain language.

Keep reading

This article is general guidance. Library features change between versions, so always check the official documentation for the version you use.

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *