/* jquery */ /* jquery accordion style*/ /* jquery init */

Learn Python - Using Functions

As an analogy think of a Lego set. You have a wide selection of bricks in all kinds of sizes, shapes and colours. These bricks enable you to build models quite quickly, just by combining the right type of bricks in the right sequence. If you change you mind, or have a new idea, the type of bricks used or their assembly sequence can be quickly changed.

In Python, as with most languages, the developer can define a set of functions. Each function has a well defined purpose and role within the overall program. In effect a function acts as a code brick. Once defined and tested a program can be assembled by calling these functions in a particular sequence.

A function can be called many times within the same program. Reusing code in this way reduces the overall number of code lines in a program, which aids code readability and debugging. In addition, related functions can be collated and stored in a library module. This module can be imported in any number of different programs.

A good place to witness function reusability is in games. At face value every game may look very different. However, many of the tasks required are very similar. Loading an image, moving an image around the screen, playing a sound, testing for key or mouse button presses, and so on can all be done with generic functions.

The more programming experience you gain, the more you'll start to recognise the sections of your programs that could be converted into functions.

A post from my Learn Python on the Raspberry Pi tutorial.