The whole class in one line each
You have a list of marks. You want the total, the average, the highest, the lowest and a ranking. You could reach in and pull out marks one position at a time, the way problem 6 did — but with two hundred students that is two hundred lines of typing, and the number changes every term.
Python already knows how to do these jobs on a whole list at once, however long it is. Each one is a single word.
| You write | You get back |
|---|---|
| sum(marks) | every mark added together |
| max(marks) | the largest one |
| min(marks) | the smallest one |
| sorted(marks) | a new list, smallest first |
| sorted(marks, reverse=True) | a new list, largest first |
sorted(marks) passes one. sorted(marks, reverse=True) passes two, and the second is given a name so Python knows what it is for. Named arguments like reverse=True are how you adjust the behaviour of a tool without changing what it works on.sorted(marks) leaves your list exactly as it was and hands back a tidy copy.marks.sort() rearranges your list where it stands and hands back nothing at all.Both are useful. But if you store the result of the second one, you have stored nothing, and the original order is gone for good. This catches experienced people, not just beginners.
sum, max and min built in, but no average. You build it: the total divided by how many there are. Dividing by anything else gives a number that looks perfectly reasonable and is wrong.And when you build a formula, Python applies the same precedence rules you learnt at school — multiplication and division before addition and subtraction. Brackets are the only way to overrule that.
What you are building
That last-but-one line is there to prove a point. After all the summarising and ranking, the original list should be sitting exactly as it started.
Build the programme
Your plan
The steps still to place
The whole programme is laid out below. Five pieces are missing. Three of them will stop the programme; two will hand you a number that looks entirely believable and is not the number you asked for.
Leave nothing on "choose…". A wrong pick does not always cause an error — sometimes it just prints something you did not expect, which is the harder kind of mistake to spot.
Run and read
Here is the whole programme. Change the marks and run it again — in particular, try a list that is not six marks long, and watch which lines cope.