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

31 March 2013

Learn Python - While Loops

One very common loop style is created with a 'while' statement. This kind of loop doesn't have a fixed number of iterations, but will repeat until a certain condition is met. Let's look at a simple example to see how it works in practice.

Suppose we want to count down from ten to one. Here's an example the loop code we'll need:

x = 10
while x > 0:
  print x
  x = x - 1
print "finished"

There are a number of interesting points here, so I'll go through them one by one. First we assign the variable 'x' a value of ten. Next we have our loop statement, complete with condition. A condition is simply a test to determine if something will evaluate to 'True' or 'False'. In this case we test the value of 'x' to see if it's greater than zero.

Notice the colon ':' at the end of the line. This character marks the start of our loop code. You'll also see the next two lines have been indented by adding some spaces before the statement. In Python every line that is indented after a loop colon will be executed every time the loop repeats.

(Note these indented lines have the same level of indentation - if they don't a Python error will be generated when the program runs.)

The last line isn't indented, which means it isn't part of the of the loop, and so will only be executed after the last loop cycle.

So, what does the code do?

Well, the first time the loop executes the value of 'x' is ten. As ten is greater than zero the conditional test 'x > 0' is 'True'. So, it will print out the value of 'x', then decrement it by one. The next time the loop repeats the value of 'x' will be nine. As nine is also greater than zero the loop will again print the value of 'x' and decrement it by one. Looping continues until 'x' is zero.

When 'x' is zero the test 'x > 0' will be 'False', and the loop exits. This means the program will continue from the first line after the loop. In this case that's the final print statement.

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

30 March 2013

Learn Python - Introducing Loops

Previously we introduced the Python language using the interpreted mode and created our first program. Along the way we discovered how to assign variables and import modules. This time we're going to investigate code loops and a closely related subject, conditional statements.

Loops are a very important concept in any programming language. Almost every program will contain at least one loop. They are especially important in graphical user interface (GUI) and game programming.

There are number of looping scenarios. One is to repeat the code inside a loop a fixed number of times. Another is to loop until a specified loop condition is satisfied. Alternatively, a loop exit command can be issued depending on a particular program state. In this and subsequent articles we'll meet all three of these scenarios.

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

29 March 2013

Learn Python - Your First Program

While using the interactive mode is fast and fun, real programs contain many lines of code. So, we'll need to use an editor and create Python source code files.

First, let's create a new Desktop folder to contain our files. Right click on the Desktop, select the Create New->Folder option. Call it 'Python' and press OK. We'll use this folder to store all the programs created in this series.

Depending on your version of the Raspberry Pi's Linux operating system comes with a Python-ready editor called Geany. As Geany understands the Python code it makes the task of creating, running and debugging your programs much easier.

(If your Pi doesn't have Geany don't worry, it's easy to install. Just follow these instructions.)

Once a file is saved with a '.py' extension Geany will colour code the source in the editor. Colour coding not only makes the code easier to read, but will also help you spot typos and errors, such as a missed string quote. The separate left-hand panel shows code symbols, including any variables.

Let's create a simple program. Open the LXDE Desktop menu and select the 'Programming->Geany' option. In the Geany window select the File->New menu option. An editor window will appear in a new tab. Now select File->Save menu option. We'll call this file 'first.py' and save it in the Desktop's 'Python' folder we created earlier. To do this you'll need to click on the 'Browse for other folders' option and select this folder.

Now we've saved an empty file we can type in the program code. It's best to save frequently as you type so you don't lose any changes - if you use the shortcut combination Ctrl-S (control key + 's' key) it only takes a second.

Here's the code:

import os, platform

print "Welcome to " + platform.system()
print "You are logged in as " + os.getlogin()
print "Your current directory is " + os.getcwd()
print "Running Python version " + platform.python_version()

On the first line we import both the 'os' and 'platform' modules, using the comma ',' character to separate each module. The following print statement lines are similar to the ones we used earlier in this series. Adding text string prefix will make the print output more descriptive.

Now it's time to run the program. Save the file then select the Build->Execute menu option, or press the F5 function key. You should see a new terminal window open and, hopefully, the output of our three print statements.

(Note: Geany can have a configuration issue on some Raspberry Pi distributions. So, if you don't see a terminal window at all, check out the 'Fix Geany' instructions here.)

Did you see a Python error message instead of the printed output?

If the answer is yes the error message should indicate where the problem might be. Carefully check all your typing, especially the string quotes and parenthesis brackets. Fix the problem and run again. Repeat the process until you see the print output. Testing and fixing source code in this manner is called debugging - all programmers spend quite a bit of time debugging their code.

And that's it, your first program. You can open the source file run it again anytime you like, or experiment by adding some Python statements of your own.

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

28 March 2013

Learn Python - Introducing Modules

Up to now we've just used some basic Python keywords and functions. However, Python has a rich set of functionality. The Standard Python Library contains an extensive collection of modules - well over 200 of them in fact.

To access all this functionality we need to load them using the 'import' keyword. Returning to our previous calculation theme for the moment let's load in the 'math' module, like this:

>>> import math

Now we can access the 'math' module's constants and functions. All we need to do is prefix them with 'math.' to indicate they belong to this module. Here's a few examples of what's possible:

>>> math.sqrt(27)
>>> math.trunc(2.46)
>>> radius = 9
>>> math.pi * (radius*radius)

The first statement finds the square root of 27 with the 'math.sqrt' function. In the second statement we truncate the number 2.46 with the 'math.trunc' function to produce 2. In the third statement we set a variable called 'radius' to be 9. The last statement, as I'm sure many of you already recognise, calculates the area of a circle, multiplying the constant 'math.pi' and the square of the 'radius' value.

Here's another useful module that provides platform information:

>>> import platform
>>> platform.system()
>>> platform.processor()
>>> platform.python_version()

With just one import statement and three module function calls we obtained the Raspberry Pi's operating system, the CPU processor type and the version of the Python language itself.

The last module we'll try, for now anyway, is the operating system 'os' module. It's a particularly useful module which can access the power of Linux. Here are just a few examples of what's possible:

>>> import os
>>> os.getlogin()
>>> os.getcwd()
>>> os.system("ls")
>>> os.system("ps")

After importing the 'os' module we use a function called 'os.getlogin' to display the login user name. Next, the function 'os.getcwd' displays the path of our current working directory, in this case it's the directory in which the terminal window is running. All useful stuff, but the best is yet to come.

It's 'os.system' that's the real star here. With this simple looking function we can run any Linux command. This means we can write a Python program to automate any number of Raspberry Pi operating system commands. We could search for files, start programs, perform backups, monitor running processes, and much more.

Here we have two simple examples. The 'ls' command is like 'dir' command in Windows, and lists the files in the current working directory (the one we displayed with 'os.getcwd'). Try replacing 'ls' with 'ls /' to see all the files in your Raspberry Pi's root directory.

The final statement shows the running processes (or programs) that belong to our session, which will include 'sh' shell scripts and the 'python' process we're using now. Try changing the 'ps' to 'ps -l' and you'll see more detail on each process.

Later in the series we'll explore more modules and the functionality they contain. For a full list of Python's standard modules visit the python.org reference pages.

As you can see, the interactive mode is a fast way to try out Python statements. Try entering this command to discover more about keywords and the language.

>>> help()

But, for now we'll exit the interactive mode with the this command:

>>> quit()

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

Learn Python - Using Functions

Python, like most programming languages, makes extensive use of functions. Functions act as containers for code. When a function is called, the code it contains is executed. Sometimes a function is defined as having one or more parameters. Parameters allow the programmer to pass in values which are processed by the function's code.

A function name should clearly indicate what the code inside will do. For example, here's a statement which calls a function with a single text string parameter:

>>> len("Hello")

The 'len' function returns the length of the input parameter. In this case the returned value is five. Let's try another example. This statement will ask the user for their name using a prompt string:

>>> name = raw_input("What is your name? ")

Here we're using the function 'raw_input' to capture the user's name. The text string we supplied as parameter will be printed as an input prompt. Whatever you type in response to this prompt is stored in the variable 'name'.

Now we can use the 'name' variable in other Python statements, like this:

>>> print "Hello " + name

Throughout this series we'll use dozens of Python's functions, and later I'll show how to define our own functions.

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

26 March 2013

Learn Python - Assigning Variables

In math equations we can assign values to symbols. We can do the same in Python using something called variables. Let's consider a simple math problem.

We've seen a mobile phone contract that offers a free phone plus plenty of free texts and call minutes. However, we are undecided whether to go for a 18 or 24 month deal. We know the price of a phone is normally £160, so let's store this value in a suitably named variable:

>>> phone = 160

We can check the value of 'phone' by using a simple print statement, like this:

>>> print phone

Having confirmed the 'phone' value is 160, we can calculate the 24 month deal, which costs £12 a month, and deduct the phone cost. We'll store the result of this calculation in a new variable called 'months24':

>>> months24 = (24 * 12) - phone

Next we'll do a similar calculation for the 18 month deal, which costs £15 a month, and again deduct the phone cost. The result is stored in another variable called 'months18':

>>> months18 = (18 * 15) - phone

Let's print out each of these deals:

>>> months24
>>> months18

The output shows how much we are really paying for those 'free' minutes and texts, after discounting the phone cost. Now let's compare the difference between these deals:

>>> months24 - months18

Now we can see the 24 month deal is only £18 more for an extra 6 months of calls and texts - a pretty good deal.

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

Learn Python - Interactive Python

Python has an interactive mode. A mode where we can type a statement and see the results immediately. It's a great place to experiment and gain confidence with the language. If you type something Python doesn't understand it will simply display an error message, and you can try again.

Python's interactive mode runs in a Linux terminal window. Two simple steps are all that's required. First open the LXDE Desktop menu on your Raspberry Pi and select the 'Other->Terminal' option. This will open a new terminal window.

Next to the '$' command prompt type 'python' and press return, as below:

$ python

You'll see a short message about the version of Python, and the interactive mode cursor '>>>' will appear. Now we can type any Python statement and press the 'enter' key to see the result.

Let's try to output a number with the 'print' keyword. Enter this statement:

>>> print 123.456

Now we'll use the same 'print' keyword to output a text string, as here:

>>> print "Hello"

Notice we've used quotes this time to tell Python this is a text string.

As Python understands numbers and mathematical symbols we can use Python as a calculator. Let's try a very simple statement:

>>> 2+2

After pressing return key you'll immediately see the result, namely 4. We can do more complex calculations, like this:

>>> (2*8) - (2*4)

Here we used symbols and brackets, just as you'd see in a math text book.

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

Learn Python - Which Python?

Python comes in two distinct versions, namely Python2 and Python3. Unfortunately for Python programmers Python3 is not backwardly compatible with Python2 source code.

The Python2 flavour - currently fixed at version 2.7 - is the most widely used and supported version. Many Linux distributions and all Mac OS X operating systems install Python2 by default, and the latest 'Wheezy' Raspberry Pi distribution includes both Python2 and Python3. In addition, a significant proportion of open-source, community-developed and third-party modules are based on Python2 code.

Many Python coders have both versions installed on their development machines. After all, Python3 has some highly desirable features, most notably full Unicode support. However, care must be taken to ensure any Python2 code doesn't break a Python3 app, and vice versa.

At some point in the future everyone may decide Python3 is the de facto standard - but we haven't reached that point just yet. The Python wiki has plenty more information on the Python2 vs Python3 question.

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

Learn Python - Why Python?

Python is the official development language of the Raspberry Pi. The complete language is already present on the official 'Wheezy' Debian Linux-based operating system image (see the Pi downloads page).

Python has a clear and easy-to-grasp syntax. Its many powerful features enable us to create useful programs with only a few lines of code. In addition to a rich collection of built-in functionality there are hundreds of specialised modules.

Modules to help you write code for tools, utilities, games, websites, smartphones, robotics, and much more. There's also a friendly and highly active community, who have created thousands of useful code samples, tips, Wiki help pages and 'how-to' videos.

As Python is free to use and distribute it's found in software companies, research laboratories and academic institutions across the world. Google developers, astronomers, robotics engineers, space scientists, nuclear physicists and bioinformatics researchers all have used Python.

Becoming proficient in Python programming will open a door to the world of software development. Python runs on just about every operating system. It can be found on PCs, tablets, smartphones, games consoles and many other small hardware devices. And the programming skills you'll learn can be applied to other languages, such as JavaScript, PHP, C, C++, C# and Java.

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

16 March 2013

Minecraft: Pi Edition Installation

Minecraft: Pi Edition is a free and Python-hackable version of Mojang's hugely successful Minecraft game, specifically created for the Raspberry Pi.

It's based around the Pocket Edition of Minecraft, a low cost version for smartphones and tablets running Apple's iOS or Google's Android operating system.

However, rather than the usual 'apt-get install' command it you'll need to download and unpack a zipped file.

How it is done? Boot up your Raspberry Pi, start the Raspbian's LXDE graphical interface, connect it to the internet and follow these steps.

Open a new terminal window

From the LXDE Desktop menu on your Raspberry Pi and select the 'Other->Terminal' option.

Ensure you're in the home directory

At the terminal command prompt type in this line and press enter (in Linux the tilde '~' character equates to the home directory):

$ cd ~

Download the Minecraft file

Now download the game file from the web using this wget command:

$ wget https://s3.amazonaws.com/assets.minecraft.net/pi/minecraft-pi-0.1.1.tar.gz

Unpack the downloaded Minecraft file

Next unpack file with this tar command (which creates a new directory called mcpi):

$ tar -zxvf minecraft-pi-0.1.1.tar.gz

Start the Minecraft game

Start the game using this command (which opens a new window):

$ ./mcpi/minecraft-pi

Unfortunately, as I discovered myself, you cannot run Minecraft from an ssh session or via a remote desktop viewer, such as TightVNC - which is a shame.

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

14 March 2013

Raspberry Pi Potpourri: March

Struggling to keep up to date with the fast moving Raspberry Pi world?

Then why not buy the Micro Mart magazine this week and read the March issue of my monthly series covering Raspberry Pi news, community events, hardware, software, games and tips.

Here are a few extracts:

Limor Fried, or Ladyada as she's known on the web, is the CEO of New York-based AdaFruit Industries. AdaFruit provide electronic components, project kits, and masses of helpful device-hacking open-source designs, construction tutorials and general tips.
High on the AdaFruit kit popularity front is the MintyBoost. It's a portable USB charging device, built from a few electronics components housed inside an Altoids tin - perfect for delivering an emergency power boost to your mobile phone.

The Model A board has been available from the Premier Farnell/element14 and RS Components for a number of weeks now.
This slightly stripped-down version of the Model B is likely to be a big seller. After all, a $25 Linux-based computer, perfectly suited to software coding, gaming and project construction, has to be the bargain of the decade.

If you're just beginning to create electronic circuit layouts you might like to mockup and evaluate your designs first. If so, hop over to CircuitLab's website to create a virtual circuit board layout and simulate its behaviour. The website also includes a list of quick-start circuits to browse and edit.

I mentioned Mojang's Minecraft: Pi Edition - the special, hackable version of Minecraft for the Raspberry Pi - in my January potpourri. Now Mojang have replaced the previous beta version with a full version of the game.

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