Add up a column, divide for the average, and keep the biggest so far, one row at a time.
Average speed, top scorer, longest song: most questions about data are a total, an average or a biggest.
Last lesson you picked rows out of the table. Now you will work out things about the rows: a total, an average, and the longest song. Each one is a variable that changes as the loop goes through the rows.
Make your prediction first. Help opens once you've locked it in.
total = 0
for n in [3, 4, 5]:
total = total + n
print(total / 3)
Follow total through the loop: what is it after each number? Then what does / 3 give?
Run it. total adds up every song's minutes; longest keeps the longest song found so far. round(x, 1) rounds to one decimal place.
import csv
with open("music.csv") as f:
songs = list(csv.DictReader(f))
total = 0
longest = songs[0]
for song in songs:
minutes = float(song["minutes"])
total = total + minutes
if minutes > float(longest["minutes"]):
longest = song
print("Average length: " + str(round(total / len(songs), 1)) + " minutes")
print("Longest: " + longest["title"] + " (" + longest["minutes"] + " minutes)")
import csv
with open("music.csv") as f:
songs = list(csv.DictReader(f))
total = 0
longest = songs[0]
for song in songs:
minutes = float(song["minutes"])
total = total + minutes
if minutes > float(longest["minutes"]):
longest = song
print("Average length: " + str(round(total / len(songs), 1)) + " minutes")
print("Longest: " + longest["title"] + " (" + longest["minutes"] + " minutes)")
The total and the longest, row by row.
Why the first song.
A total that only keeps the last song.
The first three songs are Jolene (2.7), Bohemian Rhapsody (5.9) and Billie Jean (4.9). Fill in total and the longest minutes after each one.
| song | minutes | total | longest minutes |
|---|---|---|---|
| Jolene | 2.7 | 2.7 | 2.7 |
| Bohemian Rhapsody | 5.9 | ||
| Billie Jean | 4.9 |
This should add up the minutes of every song, but it prints only 3.3, the length of the last song. Click the line that is wrong.
Print the average length of the rock songs only. len(songs) counts every song, so you need a count of your own.
Start count = 0 beside total = 0.
Put the adding inside if song["genre"] == "rock": and add 1 to count there too. Then divide by count.
Also print the oldest song and its year, in the same loop.
Copy the idea of longest: oldest = songs[0], then replace it when int(song["year"]) is smaller than int(oldest["year"]).
Print the average length of the rock songs only.
Run your program. This ticks when your code does all of the above.
Also find and print the oldest song.
Run your program. This ticks when your code does all of the above.
Ask for a genre, then print how many songs it has, their average length and its shortest song. If nobody types a genre that is there, say so instead of crashing (dividing by a count of 0 is an error).
Ask for a genre, then print its number of songs, their average length and its shortest song.
Run your program. This ticks when your code does all of the above.
Next: count every genre at once, and draw the counts as a bar chart.
Students total a column, divide for an average and track the longest song with a biggest-so-far variable, then restrict the average to one genre, find the oldest song and write genre stats that cope with no matches. About 50 minutes.
Open the teacher guide: answers, solutions, slides and a worksheet.
Read the unit primer first. Two patterns carry the lesson. The accumulator: total = 0 before the loop, total = total + x inside it (the bug task replaces instead of adding). The biggest so far: start with the first row, and replace it only when a row beats it. float() turns "3.9" into a number (minutes have decimals; years use int()). An average of some rows needs its own count, since len(songs) counts every song; with no matching rows the count is 0 and dividing by it is an error, which the Make asks students to handle. round(x, 1) is used once for tidy output.
The biggest-so-far pattern. Ask students to fill in the trace by hand before running anything; resist writing the comparison for them.
Stretch: Find the longest song of each decade (the 1980s, the 1990s...), using year // 10 * 10 for the decade.
Support: Give students the rock average with the count already added, and ask them to do the oldest song by copying the longest pattern.
Next lesson counts every genre at once with a dictionary and draws a bar chart. In pandas (Lesson 5) these become one-word methods such as .mean() and .max().