Saturday, May 11, 2013

Tutorial: Learn to program your Raspberry Pi

Tutorial: Learn to program your Raspberry Pi

Tutorial: Learn to program your Raspberry Pi


In this tutorial, we're going back to the original idea behind the Raspberry Pi: teaching people about technology. Over the next four pages, you'll get a whistle-stop tour of two programming languages that are included in Raspbian, the recommended distribution for the Pi.

If you don't have a Pi, then you can still follow along - you'll just need to install the programming languages through your distro's package manager. Don't worry if you haven't programmed anything before. We're going to start, quite literally, from scratch.

Scratch is a great language for learning the basics of programming without having t o worry about getting the text perfect. Since everything's done by dragging and dropping program blocks into your script, you don't need to remember any commands.

We're going to make a simple drawing program that lets you use the arrow keys to trace lines onto the screen. The first thing we need to do is create the code that lets us move the cat around the screen.

We'll use three separate blocks, each of which is executed when a key is pressed. Click on Control, then drag and drop When Space Key Pressed into the scripts. This creates a script that runs whenever the user presses the space key. Use the dropdown to change Space to Right Arrow, and drag Move 10 steps under it. This will let you move the cat forward by pressing the right arrow.

Next, create similar scripts that turn clockwise when the down key is pressed, and anti-clockwise when up is pressed. See figure 1 to see how it should look.

Now we can move around, we need to add a block that lets us draw. We don't want to draw all the time, so we will use Scratch's pen up and pen down actions. When the pen is down, the cat leaves a line behind it when it moves; when it's up, it doesn't.

Using variables

Figure 1

In order to let us toggle between having the pen up and down, we need the code to remember which state it's in. Programs use variables to do this.

A variable is a chunk of memory that you can put data in, and read d ata from. Before you can use a variable, you have to tell the computer to assign memory to it. We also give it a name that we can use to refer to it in commands.

Figure 2

Go to Variables, click on Make a Variable and give it a name. Once this is done, you will see a selection of commands that alter or use the variable. Now we have a way of storing data, we need to tell the computer to vary its behaviour depending on what the variable is.

We do this using an If… Else block. This asks if a statement is true. If it is, it executes the first block of code, otherwise it executes the second.

Figure 3

In our program, we'll take our variable, pen. If it's 0, we'll put the pen down, then set it to be 1, otherwise, we'll lift the pen up and set it to be 0. In this way, we can toggle between the two states, using the space bar. Take a look at figure 3 to see how this should be set up.

Note the use of the operator = in the if statement. This means the first block of code is run only if the variable pen contains (equals) 0 otherwise (else) it runs the second block.

Introducing loops

Figure 4

You can now move the cat around and draw a picture, but wouldn't it be nice if you could insert pre-defined items, for example circles? We'll add these next. Well, technically we'll add a 24-sided shape that looks pretty close to a circle.

The method to do this is move forward 10, then rotate 15 degrees, then move forward 10, then rotate 15 degrees, and keep doing this until you've completed the circle. You could put in the same two lines 24 times, and it would work, but it wouldn't be very good. It would look ugly, take a while to do, and if you decided you wanted to change the size of the circle, you'd have to do it 24 times.

Instead, we'll use a loop. This is a block that repeats itself. There are different types of loop; some keep going until some statement becomes false (a bit like an if command that gets repeated over and over a gain), but the one we'll use executes a set number of times.

Inside the loop, we just need the two commands: move forward 10 and rotate 15. Take a look at figure 4 for details. You've just completed your first Scratch program! The project file is on the DVD, and available from

Programming isn't an end in itself, but a method for getting computers to do your bidding; and now you've got started with Scratch, the only limit is your imagination. You could create the next killer game, a new productivity app or something so futuristic we don't even have a name for it yet.

To get your mind started dreaming up projects, here are a few of our favourites from around the web (if you've got Flash installed, you can run them in your web browser):

Super Mario Galaxy

Run around the world, picking up stars. ects/Dolfus555/162167


Based on the TV show. The graphics are dubious, but the gameplay is fun.

Space War 4

Old-fashioned vertical scrolling space ship shooter.

Snake Chamber

Learn about genetics and breed snakes!

Day Dream

Scratch is also a great tool for creating animations.


Scratch is great for learning the basics of programming, but sooner or later you're going to run into its limitations. Now we're going to t ake a look at a popular general-purpose language, Python.

The first thing you need to know about Python is that, unlike Scratch, it's entirely text-based. This doesn't mean that it can't create graphics, but that the program code is text rather than drag-and-drop blocks.

Python 1

To create a program, then, we just need to open up a text editor. Any text editor will work; Leafpad is included by default on the Raspberry Pi, so we'll use this, but if you continue to program, it's well worth experimenting with a few different ones to see which works best for you (Geany is quite popular with new Python programmers). Nb, word processors such as LibreOffice Write or Abiword won't work, because they will mess up the formatting.

Open a new file in Leafpad and, on the first line, add:


This line, rather cryptically called a shebang, tells the system to use the program python, in the folder /usr/bin/ to run the file. You'll need to add it to the start of all your Python programs. We can now get onto the guts of programming.

There's a long-standing computing tradition of having your first program output "Hello World!", and we're not going to break it here. Leave the second line blank (not strictly necessary, but it makes your code easier to read), and on the third type: print "Hello World!" and save your work in a file called

To run the program, you need to open a terminal and navigate to where you saved the file. Run chmod a+x to tell the system that the file is executable, and enter ./ to run it. You should see Hello World! appear on the screen. This shows us that the system is running properly, but it's not a very useful program.

As with the Scratch project, we'll ad d some user input. However, with Python we'll need to add a variable to store what the user types. Delete the Hello World line (leaving just the shebang), and add the line:

name = raw_input('what is your name? ')

This line creates the variable name, displays the prompt 'What is your name? ', and stores what the user types in name. We have to enclose this in inverted commas so that the computer knows it's a single chunk of text. We can then use this variable to make our print statement a little more personal with the line:

print 'Hello', name

Since the computer will run the commands in order, this one needs to be below the previous one. If they are the other way round, the program will throw an error because we are using a variable before we have created it. You can now save the file, and enter ./ at the command line to run the program.

Decisions decisions

This makes the program a little mor e functional, but it's still pretty lifeless. It just follows the same two steps, then finishes. To make it useful, we need to add a decision step, where the computer looks at the input, and performs different actions depending on what it finds.

Remember the if block in Scratch? Well, we can use the same thing here. The basic structure of the block is:

if <expression> :
<indent> code block

<expression> must be replaced with anything that can be true or false. For example, 1 > 2, or more usefully, num > 2 where num is a variable. In our case, we'll check if the name entered is a particular value:

if name == 'Ben' :

Why ==? Well, computers (and programmers for that matter) don't deal well with ambiguity. Each symbol or word we use should have precisely one meaning, otherwise things get confusing. = is used to assign a valu e to a variable, so we need to use something else to check equality. Again, we have to enclose Ben in inverted commas so the computer knows it's text. The colon tells it that we've finished our expression and we're about to tell it what to do.

We may want this if command to run more than one line of code, so we need a way to group code into blocks. In Python, this is done using indents (Python is more-or-less unique in this respect, and this method is a bone of contention to Python-haters). Indents can be a space or a tab, but it's really important that you always use the same throughout your project, otherwise it can get horribly confusing, since it doesn't go on the amount of indentation, but the number of indents. Personally, I use two spaces for each indent, because that's the way I was taught, and I'm too stubborn to change.

So, what do we want the computer to do if name == 'Ben'? Well, obviously, we want it to greet him in the appropriate manner:

if name == 'Ben' :
print "Ben, you're awesome"

Note the two spaces at the start of the second line. Note how we use double speech marks. This is because the text we're enclosing has an apostrophe in it. We don't want to be rude to other people, so we'll add an else block that runs whenever the if expression is false:

else :
print 'Hello', name

One last feature we'll add to our program is a loop. This will work much like the one we added to our Scratch program, except that it won't only run 24 times, it'll keep running until we tell it to stop.

We do this using a while loop and the syntax:

while <expression> :
<indent>code block

We can tell the program to stop by entering the name quit. So, our while loop will be:

while name != 'quit' :

Solving problems

Python 2

Don't ask us why, but exclamation marks are often used to mean not in programming. But this still leaves us with a bit of a problem. If we put it before name = raw_input… then it will throw an error, saying it doesn't know what name is. If we put it after, it will only ask us to enter a name once, then keep spitting out its greeting indefinitely.

To solve this, we can simply assign the empty string to name before while. This stops it erroring, and will always trigger the while expression. So, our little program now looks like this:


name = ''

while name != 'quit' :
name = raw_input('What is your name? ')

if name == 'Ben' :
print "Ben, you're awesome"
else :
print 'Hello', name

Note the four spaces before each print line. This is because they're indented twice: once for the while loop and once for the if statement. You can save this as, as before, and run it with ./

Where to go now?

If you've followed this tutorial and enjoyed writing your first programs, then you may be wondering what to do next. Well, both Scratch and Python are great languages to get started with, so first you have to pick the one that appealed to you.

If it was Scratch, the best place to start is at Here, you'll find loads of projects that other people have done that you can take a look at, and video tutorials and tours to help you learn the environment.

Python is a far mo re popular language in the real world, so you'll find many more resources to help you learn. The official website has a tutorial, which explains the language well, but can be a bit dry. There are a number of excellent books on the subject (such as Dive into Python, which is included on the DVD, or can been read for free at

Print subscribers to Linux Format can access all of our previous Python tutorials via the archives on, and our Code Concepts series, which helps introduce the key ideas behind programming.


No comments:

Post a Comment

//PART 2