Python functions - an introduction to how they work
Archive - Originally posted on "The Horse's Mouth" - 2013-11-16 17:01:18 - Graham Ellis
When I'm writing code, I'll sometimes come to a complicated algorithm and wonder just to to tackle it. I know my inputs and outputs well, but how I calculate it requires considerable thought. Take, for example, a postal delivery service in a traditional English street where the practical thing is to go up the odd numbers, cross over the road, and come back into town descending through the even numbers.
The good way to design and write algorithms like this is to put them into a named block of code - a function / method / subroutine / macro / command / proc / procedure - and you can then write, test and maintain them separately, and re-use them across a number of different programs too.
The call to the function looks like this: ex2 = postmanfirst(36,27)
and the function is defined like this: def postmanfirst(first,second): function code then
return result
When the sample call is made, the value 36 goes into a variable called first in the function, and the value 27 goes into a variable called second in the function. They are positional parameters - each is placed into the next name as the function is called, and in this form the number of parameters in the call must match the number of parameters in the def. First, second and any other variables which are set up within the function default to being local to the function - that's good news as it avoids the calling program having any risk of conflicting names.
The function decides what it should pass back in a return statement - typically it's a variable or an expression, and in the form of the call I've used that is saved into a named variable. Other variable within functions are typically lost / reset between each time the function is run; the whole thing works very nicely!