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

Learn Python on the Raspberry Pi: Building Blocks

In part three of my six part Learn Python on the Raspberry Pi series you'll discover how to defined your own functions, creating a number guessing game in the process.

Functions enable you to develop modular, well structured programs. Such programs are easier to edit, extend and debug.

If you don't have a Raspberry Pi you can still follow the series with these emulation instructions.

Here are a few extracts from Part 3:

So far all our programs have had a simple flow, from top to bottom. While this is fine for small examples, as soon as programs become longer and more complex, things tend to become more difficult.

...

A far better approach is to break the solution down into a series of identifiable steps. Each step can be designed and coded in isolation.

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.

All functions will have a pair of brackets, or parenthesis, after the name. Optionally there may be one or more parameters declared inside these brackets. Here there is just one called 'radius', which will contain a numeric radius value. Finally, there's a colon ':' at the end of the definition. As we saw last time with Python loops, a colon signifies that all the indented code below will belong to this function, and will be executed when it's called.

Creating our own functions is a major step in becoming a more accomplished programmer. Study just about any program example on the web or in a book and you'll see functions everywhere.

Next time we'll be getting much more visual. We're going to create graphical user interface (GUI) programs using another powerful Python module, Tkinter. Until then have fun with the guessing game.

Visit my Raspberry Pi page for news, reviews, advice and tutorials.

No comments: