Learn to program your Raspberry Pi

Python

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 take 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.

Your Pi ships with IDLE – a Python development environment – that allows you to input commands. It includes a handy help() command that can help you with your syntax, and also comes with its own built-in text editor, with colour-coded syntax and automatic placing of indents, to help with your programming.

Note: because Python's code is text based, you can use any text editor to create a program – Leafpad comes with the Pi, for example. Geany is another popular choice with new Python programmers. Avoid the use of word processors such as LibreOffice Writer, however, because they mess up the formatting and prevent your program from functioning correctly.

Python 1

Okay, open the Pi menu and choose Programming > Python 3. This is the command line, but we want IDLE's text editor, so choose File > New to create a new blank document. On the first line, add:

#!/usr/bin/python

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 hello.py.

To run the program, you need to open a terminal and navigate to where you saved the file (your home folder by default). First, type the following command to tell the system the file is executable:

$ chmod a+x hello.py

Next, type this command to run your program:

$ ./hello.py

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 add 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 up an error because we are using a variable before we have created it. You can now save the file, and enter ./hello.py at the command line to run the program.

Decisions decisions

This makes the program a little more 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 :
code block

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 value to a variable, so we need to use something else to check equality. Again, we have to encloseBen 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, we recommend using two spaces for each indent, because that's the way we were taught, and we're too stubborn to change – IDLE attempts to insert these automatically for you.

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 :
code block

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

while name != 'quit' :

Python 2

Solving problems

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 produce 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:

#!/usr/bin/python

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 whileloop and once for the if statement. You can save this as hello.py, as before, and run it with ./hello.py.

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 the most to you.

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

Python is a far more 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 can been read for free at www.diveintopython.net).

Subscribers to Linux Format can access more Python tutorials via the archives at www.linuxformat.com, where you'll also find our Code Concepts series, which helps introduce the key ideas behind programming.