25 Python Data Analysis Exercises for Beginners with Solutions

A student can watch hours of Python tutorials and still become stuck when asked to analyze a new dataset. The missing ingredient is often deliberate practice: interpreting a question, writing a first attempt, finding mistakes, checking numerical results and explaining why the solution works. This workbook gives you twenty-five opportunities to practise those habits independently.

These Python data analysis exercises with solutions progress from lists, loops and functions to NumPy arrays, Pandas DataFrames, CSV cleaning, statistical charts and a final miniature research project. Each problem uses fictional or synthetic data, so you can learn safely without accessing real school records, private information or paid datasets.

The learning method is intentionally active. Read the objective and sample data, write a short solution in a notebook, predict the output, test your code, then open the green Reveal worked solution panel. Explain any difference between your attempt and the verified answer before moving to the optional extension. The complete Python scripts were individually executed and the companion notebook was tested from start to finish.

How to study: Attempt each challenge before revealing the answer. Use the problem-only A4 PDF if you prefer working without solution panels. Keep a brief debugging journal of errors, their causes and how you corrected them. A successful run is valuable, but being able to explain the result is the real learning goal.

Five-module workbook overview

ModuleExercisesPrimary skillsLevel
1. Python fundamentals1–5Lists, loops, functions and arithmeticBeginner
2. NumPy6–10Arrays, vectorization and statisticsDeveloping
3. Pandas11–15DataFrames, filters, groupingDeveloping
4. CSV and data quality16–20Import, inspect, clean, exportDeveloping
5. Visualization and project21–25Charts, aggregation, capstoneIntermediate beginner
Complete modules in sequence or revise an earlier skill when an exercise exposes a gap.
Progression diagram across five modules from Python fundamentals to a full capstone project
An original overview showing how the five skill modules build on one another.

Set up Python for this workbook

Use a current Python 3 environment with NumPy, Pandas and Matplotlib. Most early exercises need only Python itself; Modules 2–5 require additional packages. You can use a locally managed Jupyter Notebook or Google Colab. For local use, install into your project environment using python -m pip install numpy pandas matplotlib.

Keep code and CSV files together in a writable project directory. Each worked solution is self-contained, even if earlier exercises used similar data. This makes it easier to restart the notebook and verify results rather than relying on variables from an unrelated exercise. The four chart activities save PNG images; use a folder where writing files is permitted.

Download the printable student workbook and answer guide

The student workbook contains the 25 problems and starter ideas without presenting the worked answers first. The complete answer guide has independently executed code, expected outputs, reasoning, common mistakes and extensions. The Jupyter notebook, Python scripts, CSV examples and chart files are also provided in the companion package.

You may also use the interactive solution panels below without downloading anything. The numerical outputs match the packaged answer guide. Where a code cell saves a chart, the expected printed result is the filename, and the actual generated plot is displayed nearby.

MODULE 1 — PYTHON FUNDAMENTALS FOR DATA ANALYSIS

Beginner Python exercises develop reliable arithmetic, conditions, loops and reusable functions. Focus on understanding what each operation measures before importing a specialist data-science library. Count and validate observations rather than guessing expected results.

Worked arithmetic example for calculating a mean of 76 from five fictional exam scores
Practice arithmetic before checking code output.

Exercise 1: Calculate the Average Examination Score

Difficulty: Beginner. Learning objective: Calculate a mean from a Python list using sum() and len().

Problem statement: Five fictional test scores are provided. Find their arithmetic average and describe what it represents.

Sample data: scores = [62, 75, 81, 92, 70]

Starter code: Use the incomplete starter below.

scores = [62,75,81,92,70]
# Calculate average

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 1

Worked solution: Independently executed, with required imports.

scores = [62,75,81,92,70]
average = sum(scores)/len(scores)
print(f"Mean: {average:.1f}")

Verified expected output:

Mean: 76.0

Why it works: Sum the five values to get 380, then divide by five. A mean can be pulled upward by a very high score, so inspect the distribution too.

Common mistake to avoid: Dividing by a fixed number when the list length changes. Try an extension: Replace the highest score with 100 and recalculate the average.

Exercise 2: Find Maximum and Minimum Daily Temperatures

Difficulty: Beginner. Learning objective: Use min() and max() to summarize extremes.

Problem statement: Identify the coolest and warmest fictional day.

Sample data: temps = [21,24,19,27,23] °C

Starter code: Use the incomplete starter below.

temps = [21,24,19,27,23]
# Print coolest and warmest

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 2

Worked solution: Independently executed, with required imports.

temps = [21,24,19,27,23]
print('Coolest:',min(temps),'°C')
print('Warmest:',max(temps),'°C')

Verified expected output:

Coolest: 19 °C
Warmest: 27 °C

Why it works: The extremes provide a quick range check, but the five days cannot establish a climate trend.

Common mistake to avoid: Confusing the positions of values with their temperatures. Try an extension: Calculate the range (maximum minus minimum).

Exercise 3: Count Scores Reaching a Threshold

Difficulty: Beginner. Learning objective: Use a loop and an if condition to count qualifying observations.

Problem statement: Count fictional scores of at least 75, including scores exactly equal to 75.

Sample data: scores = [48,65,75,90,59,75]

Starter code: Use the incomplete starter below.

count = 0
for score in scores:
    # test score

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 3

Worked solution: Independently executed, with required imports.

scores = [48,65,75,90,59,75]
count=0
for score in scores:
    if score>=75:
        count+=1
print('At least 75:',count)

Verified expected output:

At least 75: 3

Why it works: Two scores equal 75 and one is 90, so three pass this illustrative threshold.

Common mistake to avoid: Using > rather than >= and excluding a score of exactly 75. Try an extension: Count values strictly greater than 75 and explain the change.

Exercise 4: Calculate Electricity Use Percentage Change

Difficulty: Beginner. Learning objective: Compute percentage change using an initial value and a new value.

Problem statement: A fictional household used 240 kWh in one month and 198 kWh the next. Find percentage change.

Sample data: old = 240 kWh; new = 198 kWh

Starter code: Use the incomplete starter below.

old,new=240,198
# Percentage change

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 4

Worked solution: Independently executed, with required imports.

old,new=240,198
change=(new-old)/old*100
print(f'Change: {change:.1f}%')

Verified expected output:

Change: -17.5%

Why it works: Use (new-old)/old × 100; the negative result represents a 17.5% decrease. Never divide by zero.

Common mistake to avoid: Using the new value as the denominator rather than the original. Try an extension: Guard against old=0 and describe why percentage change is then undefined.

Exercise 5: Write a Reusable Mean Function

Difficulty: Beginner. Learning objective: Define a function with a parameter and return value; handle empty inputs.

Problem statement: Write a function to average any non-empty numeric list and test it with three values.

Sample data: values=[3,6,9]

Starter code: Use the incomplete starter below.

def safe_mean(values):
    # handle empty list
    pass

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 5

Worked solution: Independently executed, with required imports.

def safe_mean(values):
    if not values:
        raise ValueError('Need at least one value')
    return sum(values)/len(values)
print(f'Mean: {safe_mean([3,6,9]):.1f}')

Verified expected output:

Mean: 6.0

Why it works: A function prevents repeated arithmetic code. It raises a clear error when asked to average zero values.

Common mistake to avoid: Silently returning zero for an empty dataset, which is not its mean. Try an extension: Write a second function returning both the mean and sample size.

Module checkpoint: Test an alternative input, explain the result and document any error you corrected.

MODULE 2 — NUMPY AND NUMERICAL COMPUTING

NumPy works with arrays that can perform numerical calculations across many values. Inspect array properties, choose units carefully and understand the difference between population and sample statistics. The exercises build confidence in shape, masks and vectorized operations.

NumPy array of twelve numbers reshaped to four rows and three columns with verified weekly totals
A 4-by-3 array preserves all twelve observations.

Exercise 6: Create and Inspect a NumPy Array

Difficulty: Developing. Learning objective: Learn array construction, shape, size and dimension count.

Problem statement: Create an array of five fictional rainfall measurements. Report its structure.

Sample data: rain=[12,5,0,18,9] mm

Starter code: Use the incomplete starter below.

import numpy as np
rain = np.array([...])

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 6

Worked solution: Independently executed, with required imports.

import numpy as np
rain=np.array([12,5,0,18,9])
print('shape:',rain.shape,'size:',rain.size,'ndim:',rain.ndim)

Verified expected output:

shape: (5,) size: 5 ndim: 1

Why it works: A one-dimensional array of length five has a shape tuple (5,), a total size of five and one dimension.

Common mistake to avoid: Calling shape a number of dimensions rather than a tuple of sizes. Try an extension: Create a two-row array and compare ndim and shape.

Exercise 7: Convert Celsius Temperatures to Fahrenheit

Difficulty: Developing. Learning objective: Apply scalar arithmetic to all elements of a NumPy array.

Problem statement: Convert three fictional Celsius readings to Fahrenheit using vectorization.

Sample data: Celsius: [0,20,37]

Starter code: Use the incomplete starter below.

c = np.array([0,20,37])
# Calculate F

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 7

Worked solution: Independently executed, with required imports.

import numpy as np
c=np.array([0,20,37])
f=c*9/5+32
print('Fahrenheit:',f.tolist())

Verified expected output:

Fahrenheit: [32.0, 68.0, 98.6]

Why it works: The formula F = 9C/5 + 32 applies elementwise without a Python loop.

Common mistake to avoid: Applying +32 before scaling by 9/5. Try an extension: Convert -10°C and test whether the output is 14°F.

Exercise 8: Find NumPy Mean, Median and Standard Deviation

Difficulty: Developing. Learning objective: Compare central tendency and population/sample spread.

Problem statement: Compute mean, median, population SD and sample SD for four numbers.

Sample data: x=[2,4,6,8]

Starter code: Use the incomplete starter below.

x=np.array([2,4,6,8])
# statistics

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 8

Worked solution: Independently executed, with required imports.

import numpy as np
x=np.array([2,4,6,8])
print('Mean:',np.mean(x))
print('Median:',np.median(x))
print('Population SD:',round(np.std(x,ddof=0),4))
print('Sample SD:',round(np.std(x,ddof=1),4))

Verified expected output:

Mean: 5.0
Median: 5.0
Population SD: 2.2361
Sample SD: 2.582

Why it works: Population SD divides squared deviations by n; sample SD uses n−1. State the convention used.

Common mistake to avoid: Treating NumPy’s default ddof=0 as sample SD. Try an extension: Change the data to [2,4,6,20] and compare the mean with the median.

Exercise 9: Select Readings Above a Fictional Limit

Difficulty: Developing. Learning objective: Use Boolean indexing to find selected values.

Problem statement: From a fictional environmental sensor, select readings strictly above 40 units. This is not a safety threshold.

Sample data: readings=[21,35,44,18,55]

Starter code: Use the incomplete starter below.

readings=np.array([...])
# Boolean mask

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 9

Worked solution: Independently executed, with required imports.

import numpy as np
readings=np.array([21,35,44,18,55])
selected=readings[readings>40]
print('Above 40:',selected.tolist())

Verified expected output:

Above 40: [44, 55]

Why it works: The comparison produces a Boolean mask, which selects only entries at matching positions.

Common mistake to avoid: Calling a fictional exercise threshold an official public-health standard. Try an extension: Count qualifying readings and express the fraction of all five.

Exercise 10: Reshape Twelve Observations into Four Weeks

Difficulty: Developing. Learning objective: Reshape an array while preserving the element count.

Problem statement: Twelve observations were collected three days per week for four weeks. Form a 4×3 array and calculate weekly totals.

Sample data: values=1 to 12

Starter code: Use the incomplete starter below.

values=np.arange(1,13)
# reshape, sums

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 10

Worked solution: Independently executed, with required imports.

import numpy as np
values=np.arange(1,13)
weeks=values.reshape(4,3)
print('Shape:',weeks.shape)
print('Weekly totals:',weeks.sum(axis=1).tolist())

Verified expected output:

Shape: (4, 3)
Weekly totals: [6, 15, 24, 33]

Why it works: A 4×3 array contains 12 entries. axis=1 sums across each week’s three columns.

Common mistake to avoid: Attempting to reshape 12 values into a shape with a different total size. Try an extension: Compute daily totals across four weeks using axis=0.

Module checkpoint: Test an alternative input, explain the result and document any error you corrected.

MODULE 3 — PANDAS DATAFRAME ANALYSIS

Pandas gives rows and columns meaningful names. Practise creating a complete table, selecting records, ordering results and aggregating by group. Remember that a group average describes the selected records, not an entire real-world population.

Pandas table highlighting Leo and Mina as fictional students scoring at least 80
Filtering is based on the explicit Score threshold.

Exercise 11: Build a Student Pandas DataFrame

Difficulty: Developing. Learning objective: Create a labeled table with distinct rows and columns.

Problem statement: Represent four invented learners, subjects and scores in a DataFrame.

Sample data: Asha Math 78; Leo Science 85; Mina Math 91; Noah Science 74

Starter code: Use the incomplete starter below.

import pandas as pd
# Build df

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 11

Worked solution: Independently executed, with required imports.

import pandas as pd
df=pd.DataFrame({'Student':['Asha','Leo','Mina','Noah'],
 'Subject':['Math','Science','Math','Science'],
 'Score':[78,85,91,74]})
print('Shape:',df.shape)
print('Columns:',df.columns.tolist())

Verified expected output:

Shape: (4, 3)
Columns: ['Student', 'Subject', 'Score']

Why it works: Each list becomes a column; matching list lengths produce four complete rows. The default row index is not a student ID.

Common mistake to avoid: Assuming the DataFrame index is always a meaningful source identifier. Try an extension: Add an Age column with four fictional ages.

Exercise 12: Filter Students Who Scored at Least 80

Difficulty: Developing. Learning objective: Apply a Boolean mask to a Pandas DataFrame.

Problem statement: Select student names with scores of at least 80 from the same four-row table.

Sample data: Asha 78; Leo 85; Mina 91; Noah 74

Starter code: Use the incomplete starter below.

df = pd.DataFrame({...})
# filter

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 12

Worked solution: Independently executed, with required imports.

import pandas as pd
df=pd.DataFrame({'Student':['Asha','Leo','Mina','Noah'],
 'Subject':['Math','Science','Math','Science'],
 'Score':[78,85,91,74]})
selected=df.loc[df.Score>=80,'Student'].tolist()
print('Selected:',selected)

Verified expected output:

Selected: ['Leo', 'Mina']

Why it works: Both Leo and Mina meet the numerical rule; Asha and Noah do not.

Common mistake to avoid: Using the wrong comparison and filtering out exactly 80. Try an extension: Change the threshold to 75 and check the new selection.

Exercise 13: Sort Examination Results from Highest to Lowest

Difficulty: Developing. Learning objective: Use sort_values to order records without confusing order and ranking.

Problem statement: Sort the fictional four-row table descending by Score.

Sample data: Scores: Asha 78; Leo 85; Mina 91; Noah 74

Starter code: Use the incomplete starter below.

ordered = df.sort_values(...)
# names

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 13

Worked solution: Independently executed, with required imports.

import pandas as pd
df=pd.DataFrame({'Student':['Asha','Leo','Mina','Noah'],
 'Score':[78,85,91,74]})
ordered=df.sort_values('Score',ascending=False)
print('Order:',ordered.Student.tolist())

Verified expected output:

Order: ['Mina', 'Leo', 'Asha', 'Noah']

Why it works: Sorting reorders rows; numerical ranks require additional decisions about tied scores.

Common mistake to avoid: Calling the original row index a rank after sorting. Try an extension: Add a tied score and explore rank(method="min").

Exercise 14: Compute Average Scores by Subject

Difficulty: Developing. Learning objective: Group observations by category and calculate group means.

Problem statement: Find the Math and Science means for the shared fictional student table.

Sample data: Math 78,91; Science 85,74

Starter code: Use the incomplete starter below.

grouped = df.groupby(...)
# means

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 14

Worked solution: Independently executed, with required imports.

import pandas as pd
df=pd.DataFrame({'Subject':['Math','Science','Math','Science'],
 'Score':[78,85,91,74]})
means=df.groupby('Subject').Score.mean()
print({k:float(v) for k,v in means.items()})

Verified expected output:

{'Math': 84.5, 'Science': 79.5}

Why it works: Groupby separates rows by subject and averages each pair. Two observations per group are not a basis for population conclusions.

Common mistake to avoid: Calculating the overall mean when a subject-level average is requested. Try an extension: Also report count and minimum by subject.

Exercise 15: Calculate Percentage Scores in a New Column

Difficulty: Developing. Learning objective: Use vectorized Pandas arithmetic with row-specific denominators.

Problem statement: Three fictional tasks have different maximum marks. Calculate earned percentages.

Sample data: earned=[76,60,45]; maximum=[100,80,50]

Starter code: Use the incomplete starter below.

df["Percentage"] = ...

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 15

Worked solution: Independently executed, with required imports.

import pandas as pd
df=pd.DataFrame({'Earned':[76,60,45],
 'Maximum':[100,80,50]})
assert df.Maximum.gt(0).all()
df['Percentage']=100*df.Earned/df.Maximum
print('Percentages:',df.Percentage.tolist())

Verified expected output:

Percentages: [76.0, 75.0, 90.0]

Why it works: Each row has its own denominator, so dividing all marks by 100 would misrepresent the other tasks.

Common mistake to avoid: Ignoring zero or different maximum marks. Try an extension: Compute average percentage across the three tasks and explain its meaning.

Module checkpoint: Test an alternative input, explain the result and document any error you corrected.

MODULE 4 — CSV FILES AND DATA CLEANING

Reliable analysis starts with source inspection. Use explicit filenames, check missing entries, normalize known labels and remove only confirmed duplicate rows. Save cleaned results separately and verify exports by reading them back.

Diagram showing a fictional duplicate record removed while preserving three valid records
Inspect a repeated row before treating it as an accidental duplicate.

Exercise 16: Read a Reproducible CSV File

Difficulty: Developing. Learning objective: Write then read a small CSV and inspect its structure.

Problem statement: Create the supplied rainfall CSV, then load it using read_csv.

Sample data: TownA 18; TownB 24; TownC 11; TownD 30 (mm)

Starter code: Use the incomplete starter below.

pd.DataFrame(...).to_csv("town-rainfall.csv")
# read

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 16

Worked solution: Independently executed, with required imports.

from pathlib import Path
import pandas as pd
file=Path('town-rainfall.csv')
pd.DataFrame({'Town':['TownA','TownB','TownC','TownD'],
 'RainMM':[18,24,11,30]}).to_csv(file,index=False)
loaded=pd.read_csv(file)
print('Shape:',loaded.shape)
print('Total mm:',loaded.RainMM.sum())

Verified expected output:

Shape: (4, 2)
Total mm: 83

Why it works: Writing the file first makes the exercise reproducible without relying on an external download.

Common mistake to avoid: Assuming Python opens files from the browser download directory. Try an extension: Change the filename and check Path.cwd() before reading.

Exercise 17: Count Missing Values in Two Fields

Difficulty: Developing. Learning objective: Use isna and sums to inspect completeness.

Problem statement: Count missing Score and Attendance entries in a fictional table.

Sample data: Score=[80,None,72]; Attendance=[94,88,None]

Starter code: Use the incomplete starter below.

df.isna().sum()

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 17

Worked solution: Independently executed, with required imports.

import pandas as pd
df=pd.DataFrame({'Score':[80,None,72],
 'Attendance':[94,88,None]})
print(df.isna().sum().to_dict())

Verified expected output:

{'Score': 1, 'Attendance': 1}

Why it works: One missing value occurs in each numeric column; a missing value is not automatically zero.

Common mistake to avoid: Treating a missing mark as a score of zero without justification. Try an extension: Describe one plausible reason why missingness may not be random.

Exercise 18: Normalize Inconsistent Subject Labels

Difficulty: Developing. Learning objective: Clean spaces and map known abbreviations explicitly.

Problem statement: Standardize five category labels into Mathematics or Chemistry.

Sample data: [" Mathematics ","math","MATH","Chemistry"," chemistry "]

Starter code: Use the incomplete starter below.

labels = pd.Series([...])
# normalize

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 18

Worked solution: Independently executed, with required imports.

import pandas as pd
labels=pd.Series([' Mathematics ','math','MATH',
                  'Chemistry',' chemistry '])
mapping={'mathematics':'Mathematics','math':'Mathematics',
         'chemistry':'Chemistry'}
clean=labels.str.strip().str.lower().map(mapping)
print(clean.value_counts().to_dict())

Verified expected output:

{'Mathematics': 3, 'Chemistry': 2}

Why it works: Strip spaces, lowercase safely for matching, then map recognized labels. Unmatched values require review.

Common mistake to avoid: Assuming str.title converts MATH to Mathematics automatically. Try an extension: Add a previously unseen label and detect unmapped values.

Exercise 19: Remove Confirmed Exact Duplicate Rows

Difficulty: Developing. Learning objective: Use duplicated() and drop_duplicates() after validating repeated records.

Problem statement: A small table contains the same A,8 record twice. Identify and remove only exact repetition.

Sample data: A 8; B 6; A 8; C 7

Starter code: Use the incomplete starter below.

df.duplicated()
# clean

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 19

Worked solution: Independently executed, with required imports.

import pandas as pd
df=pd.DataFrame({'ID':['A','B','A','C'],
 'Hours':[8,6,8,7]})
print('Exact duplicates:',int(df.duplicated().sum()))
clean=df.drop_duplicates()
print('Rows after cleaning:',len(clean))

Verified expected output:

Exact duplicates: 1
Rows after cleaning: 3

Why it works: A repeated full row is a potential duplicate. Repeated IDs with different measurements may be legitimate separate records.

Common mistake to avoid: Removing every row with a repeated person ID. Try an extension: Add A with 9 hours and justify whether it is a duplicate.

Exercise 20: Export a Cleaned CSV and Read It Back

Difficulty: Developing. Learning objective: Use to_csv(index=False) and verify the exported rows.

Problem statement: Write a cleaned three-record table and confirm its shape after rereading.

Sample data: A 8; B 6; C 7

Starter code: Use the incomplete starter below.

clean.to_csv("cleaned.csv",index=False)
# verify

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 20

Worked solution: Independently executed, with required imports.

import pandas as pd
clean=pd.DataFrame({'ID':['A','B','C'],
 'Hours':[8,6,7]})
clean.to_csv('cleaned.csv',index=False,encoding='utf-8')
check=pd.read_csv('cleaned.csv')
print('Verified shape:',check.shape)
print('Total hours:',check.Hours.sum())

Verified expected output:

Verified shape: (3, 2)
Total hours: 21

Why it works: Reimporting checks the file exists and that an unwanted extra index column was not written.

Common mistake to avoid: Overwriting the raw source data rather than producing a new file. Try an extension: Compare the reloaded DataFrame with clean using equals().

Module checkpoint: Test an alternative input, explain the result and document any error you corrected.

MODULE 5 — STATISTICS, VISUALIZATION AND MINI-PROJECTS

Finish by making three authentic Matplotlib charts, summarizing grouped sales and completing a capstone. Every chart is generated by the tested Python solution rather than drawn to imitate data. Explain what the numbers support—and what they cannot prove.

Exercise 21: Create a Labeled Bar Chart

Difficulty: Intermediate Beginner. Learning objective: Use Figure and Axes to compare category magnitudes.

Problem statement: Plot three fictional subject averages as vertical bars and save the image.

Sample data: English 78; Mathematics 73; Science 81

Starter code: Use the incomplete starter below.

fig,ax=plt.subplots()
# bars

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 21

Worked solution: Independently executed, with required imports.

import matplotlib.pyplot as plt
names=['English','Mathematics','Science']
means=[78,73,81]
fig,ax=plt.subplots(figsize=(7,4))
ax.bar(names,means,color='#357b8b')
ax.set(title='Fictional subject means',ylabel='Mean / 100',ylim=(0,100))
fig.tight_layout();fig.savefig('exercise21-bar.png',dpi=150)
plt.close(fig)
print('Saved exercise21-bar.png')

Verified expected output:

Saved exercise21-bar.png

Why it works: A zero-based vertical scale prevents exaggeration; include the score unit and note these are invented averages.

Common mistake to avoid: Omitting axis labels or truncating bar axes without justification. Try an extension: Add numeric labels to each bar.

Genuine executed Matplotlib bar chart English 78 Mathematics 73 Science 81
Actual bar chart from the verified Exercise 21 code.

Exercise 22: Plot Chronological Rainfall Changes

Difficulty: Intermediate Beginner. Learning objective: Create a line plot with observations in time order.

Problem statement: Plot rainfall across five fictional months and save the figure.

Sample data: Jan–May [42,50,31,62,55] mm

Starter code: Use the incomplete starter below.

ax.plot(months,rain,marker="o")

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 22

Worked solution: Independently executed, with required imports.

import matplotlib.pyplot as plt
months=['Jan','Feb','Mar','Apr','May']
rain=[42,50,31,62,55]
fig,ax=plt.subplots(figsize=(7,4))
ax.plot(months,rain,marker='o',color='#28774f')
ax.set(title='Fictional monthly rainfall',
       xlabel='Month',ylabel='Rainfall (mm)',ylim=(0,75))
fig.tight_layout();fig.savefig('exercise22-line.png',dpi=150)
plt.close(fig)
print('Saved exercise22-line.png')

Verified expected output:

Saved exercise22-line.png

Why it works: A line helps reveal changes across ordered months, including a drop from February to March.

Common mistake to avoid: Connecting categories in arbitrary order and describing it as a time trend. Try an extension: Add a horizontal reference line at 50 mm.

Actual Python Matplotlib line plot of fictional January to May rainfall measurements
Real chart generated from the five ordered rainfall readings.

Exercise 23: Plot Study Hours Against Examination Scores

Difficulty: Intermediate Beginner. Learning objective: Use a scatter plot for two numeric variables and interpret cautiously.

Problem statement: Plot paired fictional observations without claiming causality.

Sample data: Hours [1,2,3,4,5]; Scores [52,61,66,78,88]

Starter code: Use the incomplete starter below.

ax.scatter(hours,scores)

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 23

Worked solution: Independently executed, with required imports.

import matplotlib.pyplot as plt
hours=[1,2,3,4,5]
scores=[52,61,66,78,88]
fig,ax=plt.subplots(figsize=(7,4))
ax.scatter(hours,scores,s=75,color='#385f9b')
ax.set(title='Fictional hours and scores',
       xlabel='Study hours / week',ylabel='Score / 100',
       xlim=(0,6),ylim=(40,100))
fig.tight_layout();fig.savefig('exercise23-scatter.png',dpi=150)
plt.close(fig)
print('Saved exercise23-scatter.png')

Verified expected output:

Saved exercise23-scatter.png

Why it works: The constructed points rise together, but other variables could influence genuine examination results.

Common mistake to avoid: Treating visual association as proof of a causal study effect. Try an extension: Add a sixth observation that breaks the simple trend.

Genuine executed scatter plot of study hours and fictional test scores
Association in constructed observations is not proof of causation.

Exercise 24: Summarize Fictional Sales by Region

Difficulty: Intermediate Beginner. Learning objective: Calculate revenue and group total and mean sale using groupby().agg().

Problem statement: Summarize a five-row synthetic shop dataset by North and South.

Sample data: North: Book 3×15, Pen 5×2, Book 1×15; South: Book 2×15, Pen 4×2

Starter code: Use the incomplete starter below.

sales["Revenue"]=...
# group aggregate

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 24

Worked solution: Independently executed, with required imports.

import pandas as pd
sales=pd.DataFrame({'Region':['North','North','South','South','North'],
 'Item':['Book','Pen','Book','Pen','Book'],
 'Units':[3,5,2,4,1],
 'UnitPrice':[15,2,15,2,15]})
sales['Revenue']=sales.Units*sales.UnitPrice
summary=sales.groupby('Region').agg(
 TotalRevenue=('Revenue','sum'),
 Orders=('Revenue','size')).sort_index()
print(summary.to_dict('index'))

Verified expected output:

{'North': {'TotalRevenue': 70, 'Orders': 3}, 'South': {'TotalRevenue': 38, 'Orders': 2}}

Why it works: Revenue is units multiplied by unit price per row; grouping then sums rows. Orders here means source rows, not necessarily customer orders.

Common mistake to avoid: Averaging unit prices rather than calculating actual sales revenue. Try an extension: Calculate average revenue per record and total units by region.

Exercise 25: Student Performance Data Analysis Challenge

Difficulty: Intermediate Beginner. Learning objective: Combine data import, quality checks, grouping, charting and responsible interpretation.

Problem statement: Complete a full mini-project: create or import the fictional CSV, inspect missing values and duplicates, retain valid scored rows, calculate overall and subject means, identify scores of 80+, generate a chart and export a verified clean CSV.

Sample data: 12 distinct scored fictional student records (P01–P12) across Math, Science and English; an extra exact repeat of P03 and a P13 row with missing score. Attendance for P06 is missing.

Starter code: Use the incomplete starter below.

raw=pd.read_csv("exercise25-student-performance-raw.csv")
# inspect, clean, summarize, chart, export

Your challenge: Write and test your own solution before revealing the answer. Predict the output.

Reveal worked solution and verified output — Exercise 25

Worked solution: Independently executed, with required imports.

from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
rows=[
('P01','Math',2,86,55),('P02','Math',3,90,63),
('P03','Math',4,94,72),('P04','Math',5,97,81),
('P05','Science',2,85,59),('P06','Science',3,None,68),
('P07','Science',5,95,80),('P08','Science',6,98,88),
('P09','English',1,84,61),('P10','English',3,89,70),
('P11','English',4,93,77),('P12','English',7,99,92)]
cols=['StudentID','Subject','StudyHours','AttendancePct','Score']
raw=pd.DataFrame(rows+[rows[2],('P13','English',2,87,None)],columns=cols)
raw.to_csv('exercise25-student-performance-raw.csv',index=False)
print('Raw shape:',raw.shape)
print('Exact duplicates:',int(raw.duplicated().sum()))
clean=raw.drop_duplicates().copy()
for col in ['StudyHours','AttendancePct','Score']:
    clean[col]=pd.to_numeric(clean[col],errors='coerce')
clean=clean.dropna(subset=['Score','StudyHours']).copy()
clean['AttendancePct']=clean.AttendancePct.fillna(clean.AttendancePct.median())
clean.to_csv('exercise25-student-performance-clean.csv',index=False)
print('Clean shape:',clean.shape)
print('Mean score:',round(clean.Score.mean(),4))
print('Group means:',clean.groupby('Subject').Score.mean().round(2).to_dict())
print('At least 80:',clean.loc[clean.Score.ge(80),'StudentID'].tolist())
means=clean.groupby('Subject').Score.mean()
fig,ax=plt.subplots(figsize=(7,4))
ax.bar(means.index,means.values,color='#307c87')
ax.set(title='Fictional mean examination scores',ylabel='Mean / 100',ylim=(0,100))
fig.tight_layout();fig.savefig('exercise25-capstone.png',dpi=150)
plt.close(fig)
print('Saved exercise25-capstone.png')

Verified expected output:

Raw shape: (14, 5)
Exact duplicates: 1
Clean shape: (12, 5)
Mean score: 72.1667
Group means: {'English': 75.0, 'Math': 67.75, 'Science': 73.75}
At least 80: ['P04', 'P07', 'P08', 'P12']
Saved exercise25-capstone.png

Why it works: The verified project preserves the raw file, excludes the exact repeat and missing score, imputes one attendance gap with the median as a transparent teaching decision, calculates statistics, plots group means and exports the cleaned data. No correlation proves causation, and invented results cannot describe real learners.

Common mistake to avoid: Running group averages before cleaning the duplicate; silently changing missing scores to zero. Try an extension: Restart a new kernel, rerun the project and write a 100-word conclusion acknowledging its synthetic sample.

Actual Python-generated chart for the capstone with fictional subject means 75, 67.75 and 73.75
Executed capstone chart; each subject contains four fictional scored records.
Original capstone explanatory diagram of fourteen raw rows and twelve scored observations
The capstone preserves the raw data and documents the cleaning decisions.

For this final activity, present a small research report rather than a bare table: state the synthetic nature of the data, identify the 14 raw and 12 cleaned rows, explain the duplicate and missing-score decisions, report the overall mean of about 72.17, and distinguish the observed numerical pattern from causal conclusions. The complete answer package includes the raw CSV, cleaned CSV and chart generated by Python.

Module checkpoint: Test an alternative input, explain the result and document any error you corrected.

Student self-assessment checklist

  • I can calculate basic descriptive statistics and explain their limitations.
  • I can use lists, loops, comparisons and functions independently.
  • I can describe NumPy array shape and use Boolean indexing.
  • I can create, filter, sort and group a Pandas DataFrame.
  • I can inspect CSV files for missingness and legitimate duplicates.
  • I can produce a labeled bar, line or scatter chart from actual values.
  • I can rerun a complete project and document the limitations of its data.
  • I can explain why my code works, not just copy it.

If you cannot yet complete a skill independently, return to its corresponding module and change the sample input to test your understanding. Checking these statements is for self-reflection; it is not a professional qualification or certification.

Four-week Python practice roadmap

WeekExercisesPractice priority
11–5List arithmetic, conditions, functions and descriptive interpretation
26–10NumPy arrays, vectorized calculations, statistics and reshaping
311–20Pandas, CSV file management, quality checks and validated exports
421–25Charts, group summaries, capstone, reproducibility and reporting
Adapt the schedule to your course, previous programming experience and device access.

Try a manageable daily session: solve one question, run your code, compare with the answer and write one sentence about the mistake you were most likely to make. The capstone is deliberately larger; you may need several sessions to complete and document it responsibly.

Frequently asked questions

Are these exercises suitable for complete beginners?

Yes, the first five start with basic Python lists and calculations. NumPy, Pandas and CSV skills become progressively more challenging, so take the modules in order.

Do I need Pandas before starting?

No. Module 1 requires only Python and Module 2 introduces NumPy. Pandas is introduced in Module 3 with a simple table.

Can I complete the activities in Google Colab?

Yes, most run in a standard Python notebook. File-creation exercises write to the current runtime; save important files because hosted runtime storage can be temporary.

Are NumPy and Pandas free?

Yes, these are open-source Python libraries. Installing them and using local Python is generally free, subject to your device and internet costs.

How many exercises should I practise each day?

Choose a manageable pace, often one or two with time for debugging and extensions. Accuracy and understanding matter more than a fixed daily count.

Can I download the worked solutions?

Yes. The problem-only PDF and the complete answer-guide PDF are linked near the start of this article, and the full project package includes a runnable notebook.

Why does my code print a different result?

Check source values, data types, comparisons, rounding and whether a previous notebook cell changed a variable. Run the standalone worked solution and compare step by step.

How do I improve my Python problem-solving skills?

Predict output before running code, test edge cases, explain errors, create small reusable functions and revisit earlier exercises using different fictional inputs.

Will these exercises prepare me for a data-science career?

They develop foundations but do not establish professional qualification. Further mathematics, SQL, projects, research ethics and collaboration will be important.

What should I study after the workbook?

Try the linked Pandas and visualization tutorials, complete a larger authorized dataset project, and document its source, transformations and limitations.

Conclusion: Practice Python by proving your answers

You have progressed from basic numerical reasoning through arrays, tables, file validation, grouping and graphics to a complete small project. The most important achievement is not memorizing twenty-five solutions; it is learning to formulate a problem, inspect data, check your answer and communicate a cautious interpretation.

A reproducible program should work with its own documented inputs rather than hidden earlier variables. Keep your sample files, verify exported data, explain any cleaning decisions and distinguish relationships from causation. The fictional workbook is a safe practice environment, but real projects require permission, accurate measurements and respect for privacy.

Use the printable workbook to tackle a question without looking at its answer. After you have completed the exercises, adapt one capstone chart or group summary to a new authorized dataset and write a brief report. That independent application is a stronger sign of progress than finishing the reading alone.

Verified official documentation: Python Tutorial, NumPy, Pandas, Matplotlib and Project Jupyter. Reviewed November 2026. All data are invented, and code outputs were checked by actual execution.

Optional Python learning pathways

Notes for SHS educational illustration, not official Coursera course artwork

Python for Everybody Specialization

Coursera — Optional guided introduction to Python programming and data handling.

Explore course details

Official course destination; affiliate tracking has not been verified. Pricing and course availability may vary. The exercises in this free guide do not require enrollment.

Notes for SHS educational illustration, not official Udemy course artwork

The Complete Python Bootcamp From Zero to Hero

Udemy — Optional broader Python practice for learners who want additional exercises.

Explore course details

Official course destination; affiliate tracking has not been verified. Pricing and course availability may vary. The exercises in this free guide do not require enrollment.