flowchart LR
A["Raw data"] --> B["Many clicks"] --> C["A number in the thesis"]
D["An examiner asks: how?"] -.-> B
Getting Started with Python
Getting Started with Python
Research written in code
Chapter 1
Polla Fattah
By the end of today you can
- explain why researchers write their analysis in Python;
- find your way around VS Code and interactive Python;
- run code in an interactive window and in a
.pyscript; - store values in variables and recognise basic data types;
- handle missing values (
NaNandNone); - use functions, methods, and arguments, and inspect help documentation;
- organise work in a project folder and install packages with
pip; - open the student wellbeing data and answer a first research question.
Every analysis is a chain of decisions
- which cases are kept and which are excluded;
- how an inconsistent survey answer is cleaned;
- which questionnaire items are combined into a scale score;
- which statistical model is fitted;
- how results are reported and rounded.
Each choice shapes the final numbers, and each should be open to inspection.
Point-and-click leaves no trace
Months later, not even the researcher can reconstruct exactly which cells were selected or which checkboxes were clicked.
Code is a record of the analysis
A script records every step, in order:
- your supervisor can read it;
- an examiner can audit it;
- you can re-run it in seconds when new data arrives or a mistake is found.
An analysis written as code can be proven step by step.
What Python is
Python is an open-source, general-purpose programming language renowned for clear, readable syntax.
Created in 1991 by Guido van Rossum, Python has become the global standard in data science, artificial intelligence, scientific computing, and academia.
Libraries like pandas, numpy, scipy, and seaborn turn Python into an extraordinarily powerful statistical environment.
Four reasons researchers use Python
| Property | Why it matters |
|---|---|
| built for modern data | industry-leading packages for tables, stats, and visualization |
| free and open source | anyone worldwide can inspect and run your code without software licenses |
| reproducible | identical code produces identical outputs on any operating system |
| massive global community | solutions, tutorials, and documentation for every research discipline |
The price: you type code rather than clicking menus. It feels deliberate at first, but becomes vastly faster and safer.
For users of SPSS or Excel
SPSS / Excel: click → the software silently alters data in memory
Python: write → Python executes explicit, repeatable instructions
The instructions are saved in a plain-text .py file.
Next semester, you re-run the file instead of repeating hundreds of mouse clicks.
The study behind the data
A two-year study of 600 graduate students across five faculties:
- a background questionnaire at enrollment;
- sleep, study hours, and wellbeing recorded at the end of each semester;
- a six-week wellbeing workshop, with half the students invited at random.
The questions: how do sleep, stress, and supervisor support relate to wellbeing, GPA, and dropout intentions, and does the workshop help?
The data is fictional
The student wellbeing data was generated by a computer program to emulate a realistic university cohort.
Its statistical patterns were designed by the author, not discovered in human subjects.
It describes no real individuals. Do not cite it as medical or psychological evidence about real students.
Two pieces: Python and VS Code
flowchart LR
A["You write code<br>in VS Code"] --> B["Python executes<br>the code"] --> C["Results appear<br>in VS Code"]
Python is the engine that executes calculations. VS Code (or Positron / Jupyter) is your interactive dashboard.
You type your scripts in VS Code, which delegates execution to Python.
Setting up your environment
- Download and install Python (3.10+) from python.org.
- Install VS Code from code.visualstudio.com.
- In VS Code, install the official Python and Jupyter extensions from the Extensions tab (
Ctrl+Shift+X).
Appendix A provides step-by-step guidance for Windows, macOS, and Linux.
Python as a calculator
Three nights of sleep, averaged.
Standard arithmetic operators: - + (addition), - (subtraction) - * (multiplication), / (true division) - ** (exponentiation / power)
Parentheses decide calculation order
Without parentheses, Python follows standard precedence: division occurs before addition.
Always use parentheses () to make grouping clear and unambiguous.
Store values in variables
The equals sign = is the assignment operator. It reads: “evaluate the expression on the right and assign it to the name on the left.”
Variables hold values in memory and can be referenced in later calculations.
Several values in a list
sleep = [6.5, 7.0, 5.5]
average_sleep = sum(sleep) / len(sleep)
print(average_sleep)
# 6.333333333333333Square brackets [...] define a Python list: an ordered collection of values.
sum() adds the elements; len() counts how many items are in the list.
Rules for naming variables
| Rule | Good | Invalid or discouraged |
|---|---|---|
| start with a letter | sleep_week1 |
1week (SyntaxError) |
use snake_case |
sleep_hours |
sleep hours (SyntaxError) |
| case-sensitive | sleep ≠ Sleep |
accidental mixing of cases |
| meaningful names | participant_age |
x, temp2 |
Descriptive variable names make your code self-documenting.
Reassignment replaces values silently
Assigning a new value to an existing variable name replaces the previous value without warning.
Keep variable definitions clear and avoid reusing identical names for different concepts.
Every value has a type
| Type | Name | Examples |
|---|---|---|
int |
Integer | 3, 600, -12 |
float |
Floating-point number | 6.5, 3.14159 |
str |
String (text) | "Education", "Male" |
bool |
Boolean | True, False |
The data type determines what operations are valid: numeric values can be averaged; text strings cannot.
Checking types with type()
Text requires quotation marks
Without quotes, Python assumes Education is the name of a variable.
Strings must be enclosed in single ('...') or double ("...") quotation marks.
Missing values: None and NaN
In raw Python, None denotes the absence of a value.
In numeric data tables (pandas / numpy), missing observations are represented as NaN (“Not a Number”):
Functions take input and return output
sleep = [6.5, 7.0, 5.5]
print(sum(sleep)) # 19.0
print(max(sleep)) # 7.0
print(len(sleep)) # 3
print(round(6.333, 1)) # 6.3Function calls use parentheses () containing the arguments (inputs), separated by commas.
Getting help in Python
In Jupyter or VS Code Interactive:
Python displays the docstring showing: - function signature; - description of all parameters; - return value.
Scripts preserve your thinking
Commands typed in an interactive REPL disappear when the session ends.
A Python script is a plain-text file ending in .py: - opens in VS Code; - lines can be executed individually (Shift+Enter); - the whole file can be executed top to bottom (python script.py).
Organizing your thesis project folder
thesis_project/
├── data/
│ └── students.csv
├── figures/
│ └── wellbeing_distribution.png
├── outputs/
│ └── table1_summary.csv
└── 01_explore_sample.py
Keep raw data, generated figures, and Python scripts neatly organized in dedicated folders.
Always navigate to the project root directory when executing scripts.
Packages add specialized capabilities
Python’s core is lean; specialized scientific tools live in packages.
Installing vs Importing
flowchart LR
A["pip install<br>Download book to shelf (once)"] --> B["On your hard drive"]
B --> C["import<br>Open book on desk (each script)"]
pip install downloads the code from the Python Package Index (PyPI).
import loads the package into your current running Python process.
The companion package: data2thesis
The companion package bundles all datasets for the book:
import data2thesis as dt
# Load the core cohort dataset
students = dt.students
print(students.shape)
# (600, 14)600 graduate students across 14 measured variables.
Inspecting a DataFrame
students.head() # first 5 rows
students.tail(3) # last 3 rows
students.columns # list of column names
students.info() # data types and non-null countsAlways inspect your data before running inferential statistics.
Accessing columns with bracket notation
A DataFrame is a 2D table composed of named columns.
Each single column is a pandas Series.
Research question: how old are the students?
Pandas automatically handles missing values by default (skipna=True).
The average student age is approximately 29.7 years.
Always audit missing observations
students["age"].isna() produces a boolean Series (True for missing entries).
.sum() counts the True values: exactly 1 student did not report their age.
A thesis must report both the statistic and the sample size (\(N = 599\)).
Counting categories with .value_counts()
print(students["faculty"].value_counts())
# faculty
# Arts & Humanities 148
# Social Sciences 134
# Science 125
# Business & Law 102
# Medicine & Health 91
# Name: count, dtype: int64.value_counts() summarizes frequency distributions across categorical factors.
Inspecting sample datasets: Seaborn
Seaborn includes built-in practice datasets:
import seaborn as sns
penguins = sns.load_dataset("penguins")
print(penguins.shape)
print(penguins["species"].value_counts())The same pandas methods apply to any dataset across biology, education, or psychology.
Practical lab: Chapter 1 Playground
Practice these concepts interactively in your browser with Pyodide:
- Starter code with blanks (
______) - Instant feedback and revealable hints
- Python code cells executable without local setup
Download chapter01.zip to run in VS Code on your computer.
Practical exercises 1–3: variables & types
- Store a supervisor’s sleep hours in a list and compute the rounded mean.
- Compare
type("600")andtype(600)and explain theTypeErrorwhen adding them. - Compute the mean of
pd.Series([4, None, 6])and explain howNaNis handled.
Practical exercises 4–6: cohort data
- Find the minimum and maximum student age using
.min()and.max(). - Count full-time vs part-time students using
.value_counts(). - Identify three researcher degrees of freedom hidden in point-and-click spreadsheets.
Troubleshooting common Python errors
| Error | Root cause | Fix |
|---|---|---|
NameError: name 'x' is not defined |
Typo or variable not assigned | Check spelling or assign variable above |
TypeError: unsupported operand |
Mixing incompatible types (e.g. str + int) | Convert with int() or float() |
SyntaxError: '(' was never closed |
Missing closing parenthesis | Check balance of () and [] |
ModuleNotFoundError |
Package not installed | Run pip install <package> |
FileNotFoundError |
Incorrect relative file path | Verify current working directory |
Chapter 1 Checklist
Misconceptions to leave behind
| Misconception | Better mental model |
|---|---|
| “Code is only for computer scientists” | Code is an audit log of research choices |
| “A missing value is equivalent to zero” | Missing means unknown; treat explicitly |
“pip install is needed in every script” |
Install once per computer; import in each script |
| “Interactive cells are enough” | Scripts ensure end-to-end reproducibility |
Summary
Write your thesis analysis as Python code in structured scripts so every table and figure can be independently verified from raw data.
Next: Chapter 2
In Chapter 2, we dive deeper into data structures:
- Python collections: lists, tuples, and dictionaries;
- Vectorized computation with NumPy arrays and Pandas Series;
- Indexing with
.locand.iloc(0-based indexing); - Importing real-world files: CSV, Excel (
.xlsx), and SPSS (.sav); - Constructing data codebooks and managing survey variables.
Comments explain the scientific rationale
Lines beginning with
#are comments: Python ignores them.Comments explain why an analytical choice was made.