Lecture slides

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 .py script;
  • store values in variables and recognise basic data types;
  • handle missing values (NaN and None);
  • 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

flowchart LR
    A["Raw data"] --> B["Many clicks"] --> C["A number in the thesis"]
    D["An examiner asks: how?"] -.-> B

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

  1. Download and install Python (3.10+) from python.org.
  2. Install VS Code from code.visualstudio.com.
  3. 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

2 + 2
# 4

(6.5 + 7.0 + 5.5) / 3
# 6.333333333333333

Three nights of sleep, averaged.

Standard arithmetic operators: - + (addition), - (subtraction) - * (multiplication), / (true division) - ** (exponentiation / power)

Parentheses decide calculation order

6.5 + 7.0 + 5.5 / 3
# 15.333333333333334

Without parentheses, Python follows standard precedence: division occurs before addition.

Always use parentheses () to make grouping clear and unambiguous.

Store values in variables

nights = 3
hours_per_night = 7.0
total_hours = nights * hours_per_night
print(total_hours)
# 21.0

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.333333333333333

Square 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

nights = 3
nights = 4
print(nights)
# 4

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()

hours = 6.5
faculty = "Education"
invited = True

print(type(hours))    # <class 'float'>
print(type(faculty))  # <class 'str'>
print(type(invited))  # <class 'bool'>

Text requires quotation marks

faculty = Education
# NameError: name 'Education' is not defined

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”):

import pandas as pd

sleep_with_gap = pd.Series([6.5, None, 5.5])
print(sleep_with_gap.isna())
# 0    False
# 1     True
# 2    False

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.3

Function calls use parentheses () containing the arguments (inputs), separated by commas.

Getting help in Python

help(round)

In Jupyter or VS Code Interactive:

round?

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).

Comments explain the scientific rationale

# Student self-reported sleep hours (first week of semester)
sleep_hours = [6.5, 7.0, 5.5, 8.0, 6.0]

# Calculate mean sleep, rounded to 1 decimal place for the thesis table
mean_sleep = sum(sleep_hours) / len(sleep_hours)
print(round(mean_sleep, 1))

Lines beginning with # are comments: Python ignores them.

Comments explain why an analytical choice was made.

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.

# In the terminal (run once per computer/environment):
pip install pandas seaborn data2thesis
# In your Python script (run at the top of each script):
import pandas as pd
import seaborn as sns
import data2thesis as dt

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 counts

Always inspect your data before running inferential statistics.

Accessing columns with bracket notation

ages = students["age"]
print(type(ages))
# <class 'pandas.core.series.Series'>

A DataFrame is a 2D table composed of named columns.

Each single column is a pandas Series.

Research question: how old are the students?

print(students["age"].mean())
# 29.724540901502505

Pandas automatically handles missing values by default (skipna=True).

The average student age is approximately 29.7 years.

Always audit missing observations

print(students["age"].isna().sum())
# 1

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

  1. Store a supervisor’s sleep hours in a list and compute the rounded mean.
  2. Compare type("600") and type(600) and explain the TypeError when adding them.
  3. Compute the mean of pd.Series([4, None, 6]) and explain how NaN is handled.

Practical exercises 4–6: cohort data

  1. Find the minimum and maximum student age using .min() and .max().
  2. Count full-time vs part-time students using .value_counts().
  3. 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 .loc and .iloc (0-based indexing);
  • Importing real-world files: CSV, Excel (.xlsx), and SPSS (.sav);
  • Constructing data codebooks and managing survey variables.