You ran a parkrun in 24 minutes 35 seconds. How can your app check you beat 25 minutes?
At your local parkrun, your watch shows twenty-four minutes and thirty-five seconds. You wanted to finish in under twenty-five minutes. Your app needs to compare those times. How can it give each time as a single number?
Look at this call. You know there are sixty seconds in a minute. To do the conversion, the function needs both parts of your time. The first input, twenty-four, goes into the minutes parameter. The second, thirty-five, goes into the seconds parameter.
Watch the caller send one minute and ten seconds. The subroutine multiplies one by sixty and adds ten. Return sends seventy back to the caller, so the call itself gives the value seventy. A subroutine that returns a value like this is a function.
The caller now runs finish equals to seconds with two minutes and five seconds. The function calculates one hundred and twenty-five and returns it. What happens next in the caller? Pick an answer.
Read the function first. It takes minutes and seconds, calculates the total and returns it. Below it, the first call stores your parkrun time in finish. The second call stores the twenty-five minute target in target. The last line checks whether finish is less than target.
Multiply twenty-four by sixty to get one thousand four hundred and forty. Add thirty-five and store one thousand four hundred and seventy-five in finish. The target call converts twenty-five minutes and zero extra seconds to one thousand five hundred. Finish is less than target, so the comparison gives true.
Now your time is nineteen minutes and forty-five seconds. The same function returns the total in seconds, and the caller compares it with one thousand two hundred. Pick the returned number and the result of the less-than test.
With return, the caller gets the number and can compare it with the target. If you replace return with print, Python displays the number, so the function might look as though it worked. But the call gives you None, and comparing None with the integer target using less than causes an error.
In the function, total is a local variable. Its scope is the function body, so the caller cannot use the name total to access that variable. Its lifetime runs from assignment until the call ends. Each call has its own total, so one call cannot overwrite another call’s local variable.