Writing the calculation once
You worked out a percentage in problem 3. If you now need one for each student, and again for the class as a whole, and again next term, you can copy those lines around — and every copy is a place where somebody will later fix the formula in three files and forget the fourth.
A function is the calculation written down once, given a name, and used wherever you need it.
def announces a new tool and names it. The names in the brackets are its parameters — empty boxes that get filled at the moment you use it. The indented lines are the body, exactly like the block under an if.Running these three lines calculates nothing. It only teaches Python what
percentage means. The work happens later, when you call it.return hands a value back to whoever asked, so it can be printed, stored, or fed into something else.print puts characters on the screen and hands back nothing.A function that prints instead of returning appears to work — the numbers are right there on screen. But the value never reaches the line that asked for it, so what comes back is
None, Python's word for nothing at all. Watch for output arriving in a strange order and the word None where a number should be. That pairing is the signature of this mistake.percentage(78, 100) puts 78 in the first parameter and 100 in the second. Python does not check that the order makes sense — it cannot know which number is which. Swap them and you get a percentage of the wrong thing, with no complaint at all.Give too few and it does object: a parameter with nothing to fill it is one of the few mistakes a function will not let pass.
share exists only while the function is running. Ask for it outside and Python has never heard of it. That is a feature, not a restriction — it means a function cannot quietly interfere with the rest of your programme.What you are building
Four percentages, one formula. The last line asks the same question of the whole class by handing over the total scored and the total available.
Build the programme
Your plan
The steps still to place
The whole programme is laid out below. Five pieces are missing. Only two of them can stop the programme; the rest hand you a number and let you decide whether to believe it.
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. The marks and the paper total are yours to change. If you set the paper total to something other than 100, the percentages stop matching the marks — which is the point of working them out at all.