Introduction and starting from scratch
Note: Our learn to program your Raspberry Pi tutorial has been fully updated. This feature was first published in May 2013.
In this tutorial, we're going back to the original idea behind the Raspberry Pi – namely, teaching people about technology. Over the course of this article, 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 if you're running Linux – 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.
Starting from Scratch
Scratch is a great language for learning the basics of programming without having to 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 sprite around the screen.
We'll use three separate blocks, each of which is executed when a key is pressed. Click the yellowControl button, 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, click the blue Motion button 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. Check out figure 1 below 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
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 data 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.
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.
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 spacebar. 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
You can now move the cat around and draw a picture, but wouldn't it be nice if you could insert predefined 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 again), 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 above for details.
Congratulations – you've just completed your first Scratch program! The project file is on the Linux Format DVD, and available from http://ift.tt/TYHE0D.
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
- Wipeout: Based on the TV show. The graphics are dubious, but the gameplay is fun
- Space War 4: Old-fashioned vertical scrolling space shooter
- Snake Chamber: Learn about genetics and breed snakes!
- Day Dream: Scratch is also a great tool for creating animations
Python
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.
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 <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 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 <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
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 http://ift.tt/LpNyAz).
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.
http://ift.tt/1Jdvuwb
No comments:
Post a Comment