🐍 Python for kids · Class 7 · Lesson 18 of 18 · Free
Capstone: Analyse Real Data with Python
⏱ About 45 minutes · ▶ run real Python here — nothing to install · no sign-in
In this lesson you will
- Load a CSV file into a list and clean out bad rows with try and except.
- Analyse data with statistics, dictionaries and key=lambda.
- Present the findings as a neat report with a text bar chart.
Your school ran a reading challenge. The teacher has a file of names, houses and books read. Which house won? Who is the top reader? Is any data wrong? Today you answer these questions like a real data analyst, using only Python.
What are the steps of a data analysis project?
Data analysts follow four steps: load, clean, analyse and present. You will use every Class 7 skill for them.
Load means reading the data from a file. Our file is a CSV, with commas between the values.
readlines() gives every line. The first line is the header with column names, so we skip it with [1:].
split(",") then turns each line into a small list, like ["Aarav", "Red", "7"].
▶with open("reading.csv", "w") as f:2 f.write("name,house,books\nAarav,Red,7\nDiya,Blue,12\nRohan,Blue,abc\n")34rows = []5with open("reading.csv") as f:6 lines = f.readlines()7for line in lines[1:]:8 rows.append(line.strip().split(","))9print(len(rows), "rows loaded")10print(rows)
No variables yet.
▌✏️ Change this code and run it yourself
3 rows loaded [['Aarav', 'Red', '7'], ['Diya', 'Blue', '12'], ['Rohan', 'Blue', 'abc']]
💡 Real CSV files can have thousands of lines. The same loop works, it just runs longer.
How do I clean messy data in Python?
Real data is messy. Someone typed "abc" instead of a number of books for Rohan.
int("abc") raises ValueError. We catch it, report the bad row, and skip it with continue.
Good rows become dictionaries. Named fields like r["books"] are easier to read than r[2].
Skipping bad row: Rohan abc
5 clean rows
{'name': 'Aarav', 'house': 'Red', 'books': 7}
💡 Never delete strange data silently. Print it, so a human can check and fix the original file.
How do I find the average and the top scorer?
Now we analyse. A list comprehension pulls out just the book counts.
statistics.mean() and median() describe the class in one number each.
max() with key=lambda finds the whole record of the top reader, and sorted() makes a ranking.
Total books: 44 Average: 8.8 Median: 9 Top reader: Diya with 12 Diya 12 Sana 11 Meera 9 Aarav 7 Kabir 5
How do I group data and count totals with a dictionary?
Which house read the most? We need a total for each house, so we group the records.
A dictionary maps each house to its running total. get(house, 0) gives 0 the first time a house appears.
This group-and-total pattern is one of the most used ideas in all of data analysis.
▶readers = [("Red", 7), ("Blue", 12), ("Red", 9), ("Green", 11)]2house_total = {}3for house, books in readers:4 house_total[house] = house_total.get(house, 0) + books5print(house_total)6winner = max(house_total, key=lambda h: house_total[h])7print("Winning house:", winner)
No variables yet.
▌✏️ Change this code and run it yourself
{'Red': 16, 'Blue': 12, 'Green': 11}
Winning house: Red
💡 max() on a dictionary loops over its keys. The lambda tells it to compare their totals.
How do I draw a bar chart in Python without any library?
A picture shows patterns faster than numbers. Repeating a symbol makes a simple bar: "#" * 5 is #####.
ljust(6) pads each name to the same width, so all the bars start in one straight line.
Big data tools draw real charts, but the idea is exactly the same: one bar per value.
▶house_total = {"Red": 16, "Blue": 12, "Green": 14}2for house, total in house_total.items():3 print(house.ljust(6), "#" * total, total)
No variables yet.
▌✏️ Change this code and run it yourself
Red ################ 16 Blue ############ 12 Green ############## 14
How do I put the whole project together?
A finished project splits the work into functions, one per step. Each function is short and easy to test.
Read the program from the bottom: load, clean, analyse, then report. That is the analyst's journey.
Try changing the data in the file text. Add yourself as a reader and run it again!
Check this row: Rohan abc Readers: 6 | Average: 8.7 Top reader: Diya Blue #################### 20 Red ################ 16 Green ################ 16
💡 Every part here comes from an earlier Class 7 lesson: functions, files, exceptions, dictionaries, lambda and modules.
🤔 Predict the output
Think like Python: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
line = "Diya,Blue,12\n"
parts = line.strip().split(",")
print(len(parts), parts[2] + parts[2])Question 2. What does this print?
totals = {}
for h in ["Red", "Blue", "Red", "Red"]:
totals[h] = totals.get(h, 0) + 1
print(totals)Question 3. What does this print?
good = 0
for v in ["8", "x", "5", ""]:
try:
good += int(v)
except ValueError:
good += 0
print(good)🧩 Your challenge
Analyse Mumbai's monsoon rainfall (in mm). The file text has one bad value, "NA". Load it, skip the bad row with a message, then print the total rainfall, the average rounded to 1 place, the wettest month, and a bar chart with one # for every 100 mm.
Skipping Aug - value is NA Total: 1780 mm Average: 445 mm Wettest month: Jul Jun ##### 520 Jul ######## 840 Sep ### 330 Oct 90
⚠️ Common mistakes (and how to fix them)
❌ Wrong
lines = ["name,books\n", "Aarav,7\n", "Diya,12\n"]
total = 0
for line in lines:
name, books = line.strip().split(",")
total += int(books)
print(total)ValueError: invalid literal for int() with base 10: 'books'
✅ Right
lines = ["name,books\n", "Aarav,7\n", "Diya,12\n"]
total = 0
for line in lines[1:]:
name, books = line.strip().split(",")
total += int(books)
print(total)The first line is the header, and int("books") is impossible. Skip the header with lines[1:].
❌ Wrong
rows = [["Aarav", "7"], ["Diya", "12"], ["Kabir", "5"]]
top = max(rows, key=lambda r: r[1])
print("Top reader:", top[0])No error message – but it says Aarav, though Diya read 12 books.
✅ Right
rows = [["Aarav", "7"], ["Diya", "12"], ["Kabir", "5"]]
top = max(rows, key=lambda r: int(r[1]))
print("Top reader:", top[0])The numbers are still strings. Strings compare letter by letter, so "7" beats "12" because 7 comes after 1. Convert with int().
❌ Wrong
import statistics
scores = {"Red": [7, 9], "Yellow": []}
for house, books in scores.items():
print(house, statistics.mean(books))StatisticsError: mean requires at least one data point
✅ Right
import statistics
scores = {"Red": [7, 9], "Yellow": []}
for house, books in scores.items():
if books:
print(house, statistics.mean(books))
else:
print(house, "has no data yet")You cannot average an empty list. Check that a group has data before doing maths on it.
📌 Remember
- Data analysis has four steps: load, clean, analyse and present.
- Read a CSV with readlines(), skip the header with [1:], and split(",") each line.
- Use try and except to skip bad rows, and print them so a human can check.
- Convert text to numbers with int() before you add, compare or sort.
- Group with a dictionary and get(key, 0); find the top with max(key=lambda).
- "#" * n draws a quick text bar chart to present your findings.
Finished the quiz and the challenge?
Questions students ask
What do real data scientists use?
They use Python libraries like pandas for tables and matplotlib for charts. Those tools do the same steps you did here, just faster.
Where can I find real data to analyse?
Collect your own: class marks, cricket scores, daily temperatures or pocket money. India's open data site data.gov.in also has free files.
Why not just delete the bad rows by hand?
With thousands of rows that is impossible. A program that reports bad rows is faster and never gets tired.
What should I build next?
Try a survey of your class's favourite sports, or track your screen time for two weeks. Then report the averages and draw a bar chart.