Putting it all together
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Putting it all together
- You now know variables, input,
if, loops, lists, functions, and dictionaries. - A real program combines these small pieces into one useful tool.
- In this lesson you build a tiny class-scores analyzer, one function at a time.
The plan
- We have a list of test scores, like
[70, 90, 50, 80]. - We want three answers: the average, how many passed, and a short summary.
- We will write one small function for each job, then they work together.
Handy built-ins for lists
- Python gives you ready-made helpers that work on a list of numbers.
len(x)counts the items,sum(x)adds them,max(x)/min(x)find the largest / smallest.- Use them instead of writing a loop every time.
scores = [70, 90, 50, 80]
print(len(scores)) # 4
print(sum(scores)) # 290
print(max(scores)) # 90
print(min(scores)) # 50
A pattern you will reuse: count items that pass a test
- A very common job: loop a list, and count the items that pass some test.
- Start a counter at
0, and add1each time theifis true. - Here we count the long words; soon you will count the passing scores.
def how_many_long_words(words, min_length):
count = 0
for w in words:
if len(w) >= min_length:
count = count + 1
return count
print(how_many_long_words(["hi", "hello", "hey", "howdy"], 4)) # 2
Now you try
- Build the analyzer in three steps:
average,count_passing, thenstats. - Each function is small. Together they turn a list of scores into real answers.
- Press Check answer after each one.
Write average(scores) that returns the average (mean) of a list of numbers: the total divided by how many. If the list is empty, return 0 (so it does not crash). Example: average([2, 4]) is 3.0.
Click Run to see the output here.
Write count_passing(scores, pass_mark) that returns how many scores are greater than or equal to pass_mark. Loop the list and count. Example: count_passing([40, 50, 60], 50) is 2.
Click Run to see the output here.
Write stats(scores) (assume at least one score) that returns a dictionary with three keys: "highest", "lowest", and "average". Example: stats([70, 90, 50, 80]) returns {"highest": 90, "lowest": 50, "average": 72.5}.
Click Run to see the output here.