Python functions – avoid repeating code
Programming languages share a concept that has aided programmers for decades: functions. The idea of a function, loosely speaking, is to create blocks of code that will perform an action on a piece of data, transforming it as required by the programmer, and returning the transformed data back to the main body of the code script. We've already been introduced to some of Python's built-in functions in the last few chapters: the int
function, for instance, will convert a string, or a floating number into an integer. Now it's time to write our own.
Functions are used because they solve many different needs within programming. Functions reduce the need to write repetitive code, which, in turn, reduces the time needed to create a script. They can be used to create ranges of numbers (the range
function), or to determine the maximum value of a list (the max
function), or to create an SQL statement to select a set of rows from a feature class (see later). They...