Playground: Chapter 1
Getting Started with Python
This page practises the ideas of Chapter 1 in four parts. Practise the chapter works through the book’s exercises, with starter code, hints, and solutions. Go further goes beyond the book, with new questions and datasets. Check your understanding asks short questions whose answers open with a click. Do it yourself gives open tasks with an empty code space and no answers: you decide how to write the code, as you will in your own thesis.
Python runs right in your browser via Pyodide, so the first run can take a few seconds while the Python environment loads. In the exercises, replace each ______ with your own code and press Run Code.
Practise the chapter
These are the exercises at the end of Chapter 1, with the same numbers.
Exercise 1: A supervisor’s sleep
A supervisor sleeps 8, 7.5, 6, and 7 hours on four nights. Store the numbers in a list called supervisor_sleep and find the average, rounded to one decimal place.
The number of items in a Python list is found with len(). The second argument of round() is the number of decimal places.
supervisor_sleep = [8, 7.5, 6, 7]
average_sleep = sum(supervisor_sleep) / len(supervisor_sleep)
round(average_sleep, 1)The average is 7.125 hours, which rounds to 7.1. Storing the values in a list preserves them in memory, so you can calculate standard deviations, medians, or plot them later without retyping the numbers.
Exercise 2: Text and numbers
Check the types of "600" and 600 with Python’s built-in type(), and explain the difference.
Pass the integer 600 (without quotes) to type().
print(type("600"))
print(type(600))"600" is str (a string): text that happens to consist of numeric digits. 600 is int (an integer): a number Python can calculate with. Try "600" + 1 in Python to see the result: Python raises a TypeError because it strictly protects data integrity and refuses to add a number to text.
Exercise 3: Missing values and calculations
In data analysis, missing observations are represented as missing data (NaN or None). When using pandas, calculate the mean of [4, None, 6] and explain how pandas handles missing values.
Pandas Series objects have a method named .mean() that calculates the arithmetic average while skipping missing entries by default.
import pandas as pd
values = pd.Series([4, None, 6])
values.mean()Pandas converts None in numeric vectors to NaN (“Not a Number”). By default, values.mean() skips missing values (using skipna=True), producing 5.0. When reporting statistics in your thesis, always state both the summary statistic and the number of missing observations (values.isna().sum()).
Exercise 4: The youngest and the oldest student
Using the students DataFrame, find the age of the youngest and the oldest student.
The two methods on a pandas Series are .min() and .max().
print(students["age"].min())
print(students["age"].max())The youngest student is 23 and the oldest is 52. Checking minimums and maximums is a critical first step in data validation: an age of 2 or 200 immediately reveals data entry errors.
Exercise 5: Part-time students
Using the .value_counts() method, find out how many students are studying full-time versus part-time (the variable is study_mode).
Call .value_counts() on the column students["study_mode"].
students["study_mode"].value_counts()177 of the 600 students study part-time, and 423 study full-time.
Exercise 6: Decisions without a record
Think of an analysis you have done, or read about, using a point-and-click spreadsheet. List three decisions in it that a reader could not verify without a written record. Write your answer first, then open the model answer.
Any three of these, or similar ones from your own experience: which outlier cases were deleted and under what criteria; how missing survey answers were imputed or filtered; which survey items were reverse-coded; where demographic age categories were cut; and which specific statistical models were tried before arriving at the final report. In a spreadsheet, these transformations leave no audit trail. In a Python script, every transformation is documented in executable code.
Go further
These exercises go beyond the basic chapter examples.
Exercise 7: Vectorized calculations with a whole week
Pandas Series allow arithmetic across every observation at once. A student slept 6.5, 7, 5.5, 8, 7.5, 6, and 9 hours over a week. Convert the week to minutes, find the difference between the longest and shortest night in minutes, and count the nights under 7 hours.
Multiply hours by 60 to obtain minutes. The comparison week < 7 creates a boolean Series where True equals 1 and False equals 0; .sum() counts the True values.
import pandas as pd
week = pd.Series([6.5, 7, 5.5, 8, 7.5, 6, 9])
minutes = week * 60
print(minutes)
print(minutes.max() - minutes.min())
print((week < 7).sum())The longest and shortest night differ by 210 minutes (3.5 hours), and 3 of the 7 nights are under 7 hours. Vectorized operations and boolean counting are fundamental tools throughout this book.
Exercise 8: Master’s and PhD proportions
Find how many students are enrolled in each degree programme, and calculate the proportion of PhD students.
Divide the PhD count by the total sum of counts using .sum(). Alternatively, you can run students["programme"].value_counts(normalize=True).
counts = students["programme"].value_counts()
print(counts)
print(counts["PhD"] / counts.sum())426 students are Master’s students and 174 are PhD candidates, meaning 29.0% are PhD students.
Exercise 9: Reading Python error messages
Every Python programmer encounters error messages daily. The code below contains three common syntax and name errors. Inspect and fix each one:
Check for missing closing parentheses ) on lines 2 and 4, and check the spelling of sleep_week on line 3.
sleep_week = [6.5, 7, 5.5, 8]
print(round(sum(sleep_week) / len(sleep_week), 1))
print(sum(sleep_week))
print("wellbeing".upper())Python gives helpful tracebacks: a SyntaxError: '(' was never closed points to unclosed brackets, while NameError: name 'sleep_wek' is not defined points to typos in variable names.
Exercise 10: Inspecting Seaborn’s built-in penguins dataset
Seaborn includes sample datasets for practice. Load the penguins dataset, inspect its first rows, its total shape, and count penguins by species.
Use .head() to view the first five rows, and .value_counts() on the species column.
import seaborn as sns
penguins = sns.load_dataset("penguins")
print(penguins.head())
print(penguins.shape)
print(penguins["species"].value_counts())The dataset contains 344 rows and 7 columns, covering three penguin species: Adelie (152), Gentoo (124), and Chinstrap (68).
Check your understanding
Answer each question in your own words first, then click to see a model answer.
1. What is the difference between running code in an interactive Python REPL/cell versus writing a .py script?
Commands run in an interactive REPL or temporary scratch cell are ephemeral. Code written in a version-controlled .py script or Quarto document is saved permanently, can be audited, executed from top to bottom, and reproduced by collaborators.
2. Why does values.isna().sum() matter before computing statistical summaries?
Pandas statistical methods like .mean() and .median() skip missing values (NaN) by default. If 200 out of 600 students did not answer an item, .mean() will still return a number based only on the 400 respondents. Checking .isna().sum() ensures you know and report the true sample size (\(N\)) for every variable.
3. What is the difference between pip install and import?
pip install package_name downloads and installs a library from PyPI onto your machine’s environment (done once per environment). import package_name loads that installed library into the active Python session (done at the top of each script).
4. Why does Python use 0-indexed positions (e.g. list[0])?
In Python and many programming languages, indices represent the distance or offset from the start of the collection. The first element is at offset 0 from the start, so it is accessed at index [0].
5. Why is a Python script called an audit trail of scientific decisions?
Every transformation—from reading the raw CSV file to handling outliers, encoding survey factors, computing descriptive statistics, and fitting models—is explicitly written out in sequence. Anyone can run the script and obtain identical results without relying on unrecorded mouse clicks.
Do it yourself
These tasks have no starter code and no answers. Write your own code, as you would for your thesis. The data (students and semesters) is already loaded in your environment.
1. Write a short script that stores your hours of sleep for seven nights in a list or pandas Series, and computes the average, minimum, maximum, and the number of nights under 7 hours.
2. Using students, report three key descriptive facts about the sample using single lines of pandas code (for example: the number of distinct departments, the proportion of female students, and the median age).
3. Load the built-in tips dataset from seaborn (sns.load_dataset("tips")), print its dimensions (.shape), and calculate the average total bill grouped by whether the customer was a smoker or non-smoker.
4. On your own computer: Create a dedicated thesis project folder with a data/ directory. Place students.csv in data/, open the folder in VS Code, and write a script analysis.py that loads the data using pandas and prints the shape and column names.
Work on your own computer
The starter project contains the data and all four parts of this playground as executable Python scripts: starter exercises with blanks, solutions, and open tasks.
- Download chapter01.zip, unzip it, and open the folder in VS Code.
- Run
pip install data2thesis pandas seabornto set up your Python environment.