Raspberry Pi Projects (2014)
Part I. Getting Started with the Raspberry PiChapter 2. Introductory Software Project: The Insult Generator
by Dr. Andrew Robinson
In This Chapter
• Writing and running your first Python program
• Storing data to variables
• Holding text in strings
• Printing messages on the screen
• Creating functions
• Getting input from the user
• Conditional behaviour with if statements
• Repetition with loops
This project is just a bit of fun for you to get going with your first program. The program generates a comedy insult by combining a verb, an adjective and a noun at random. In other words, you’ll make your highly sophisticated Raspberry Pi display something like “Your brother is a big old turnip!”
By beginning with something simple, you can start having fun without having to write too much code, and after you’ve got something running, you can change it to make it more sophisticated. In fact, professional computer programmers often take a similar approach: They write something simple and test it, and then add more and more features, testing as they go.
It’s also useful to look at sample code, work out what it is doing and then change it to suit your requirements. Most professional programmers work this way too. Feel free to experiment and customise the projects in the book. Just remember to keep a copy of the original program so that you can go back to it if your modifications don't work.
This chapter helps to get you started programming the Raspberry Pi and, as such, it has the most theory. Do stick with it, and at the end of the chapter, you’ll have the knowledge to make the program your own. There’s a lot in this chapter, but you needn’t do it all in one go; sometimes it’s better to come back after a break. Programming is no less creative than painting a picture or knitting, and like these hobbies, you need to spend an hour or two covering the basics before you can produce a masterpiece!
In this chapter, you will learn how to enter a Python program and run it. You’ll also learn about various aspects of the Python language.
Running Your First Python Program
Many people use a word processor to produce documents with a computer because it provides features such as spelling and grammar checkers. However, there is nothing to stop you from using a simple text editor like Notepad in Windows, TextEdit on an Apple Mac or LeafPad on the Raspberry Pi. Similarly, when writing code, you can just type it in a text editor, or you can use an Integrated Development Environment (IDE). Similar to a spell checker in a word processor, an IDE checks the syntax (to ensure that it will make sense to the computer) and has other helpful features to make writing code a pleasure!
Just as there are lots of different word processors, there are a number of IDEs for Python. For the simple example in this chapter, you are going to type your first Python program into IDLE. IDLE is good for beginners because it is simple and can often be found wherever Python is installed, including on the Raspberry Pi.
To start IDLE, click the menu in the bottom-left corner of the screen (where the Start button is in Microsoft Windows), choose Programming, and then click IDLE, as shown in Figure 2.1.
Figure 2-1: Starting IDLE.
The Raspberry Pi comes with two versions of IDLE. IDLE 3 uses Python version 3.0, which contains more functionality and has subtle changes to parts of the language. The examples in this chapter are written for Python 2 (that is, IDLE). If you use the examples in the book without changing them you’ll receive errors.
You will see the IDLE window appear in interactive mode. In this mode, what you type is interpreted as soon as you press Return, which is a great way to try out your Python code. To see how this works, follow these steps:
1. Type the following code:
print (“Hello World”)
Computers are less forgiving of mistakes than humans, so make sure that you type the code exactly as it appears in this and other examples in this book.
2. Press Return. You should see Python run your first line of code and display the greeting shown in Figure 2.2.
Figure 2-2: Python says “Hello World”.
Many programmers write a “Hello World” program whenever they learn a new language. It is about the simplest program and is a good way to check that it is possible to write some code and then run it. It dates back to the first tutorials of how to program in the 1970s. There’s even an equivalent in hardware to “Hello World” that you’ll see in Chapter 9, “Test Your Reactions”.
If you got the result shown in Figure 2.2, then welcome to the club – you’re now a computer programmer! If not, go back and make sure that you typed the code exactly as shown in the example (sometimes even the number of spaces matter in Python), because computers need to be told precisely what to do. This strict rule means that unlike English, a statement can only be interpreted with one meaning.
Saving Your Program
IDLE allows you to save your code so that you don’t have to re-enter it each time you want to run it. Just follow these steps:
1. Create a blank file for your program by selecting New Window from the File menu, as shown in Figure 2.3.
Figure 2-3: Creating a new file.
2. Enter the following code and then click the Run menu and choose Run Module, or press F5.
message = “hello world from a saved file”
3. Python displays a message that says, “Source Must Be Saved”, as shown in Figure 2.4. Click OK.
Source is an abbreviation for source code, which is another way of saying the program you’ve entered.
Figure 2-4: Python prompts, “Source Must Be Saved”.
4. Type in a filename (for this example, you can just call it hello.py), and then click Save as shown in Figure 2.5.
5. After IDLE has saved your code, you will see a message saying RESTART (Python does this so you know you’re always starting from the same consistent point), and then your code will run in the Python Shell window, as shown in Figure 2.6. If you’ve made a mistake, you’ll see an error – correct it and then choose Run Module again.
When you save your code, IDLE adds .py to the end of the filename. This is the file extension for Python source files (just as Word adds .doc to documents).
Figure 2-5: The Save As dialogue box in IDLE.
Figure 2-6: IDLE running Python code from a file.
Generating an Insult
Now that you’ve successfully run your first program, it’s time to write something more interesting – in this case, the computer will generate its own message to print. Type the following code in a new file, save it and then run it:
from random import choice
adjectives = ["wet", "big"]
nouns = ["turnip", "dog"]
print ("You are a")
adjective = choice (adjectives)
print (choice (nouns))
When you run this program, you should see a message similar to “You are a big turnip” displayed. Run the program a few times, and you should see a variety of insults, built at random!
You can use the keyboard shortcut F5 to run the program. However, ensure the editor window containing your program has focus (is active) by clicking it before pressing F5 so IDLE knows the correct code to run.
You’ll be changing the program to display a personalised message later in this chapter, but before you do, it’s worth examining the code more closely. The following subsections describe what the different lines of the program do.
Looking at how other people’s code works is useful when you’re learning to program, and the World Wide Web is a good source of many examples.
Variables are used to store data. Creating a variable is like getting a cardboard box to reserve some storage space and writing a unique label on it. You put things in the box for storage and then get them out again later. Whenever you access the box you use its unique label.
Let’s start with something simple to illustrate variables:
message = "hello"
The equals sign means assignment, and tells Python to assign (or store) what is on the right-hand side in the variable named on the left – in this case, the characters h, e, l, l and o are stored in the variable named message.
The “ speech marks (also known as quotation marks in some parts of the world) tell Python to treat the enclosed characters as a string of letters rather than try to understand the word as an instruction.
To display text on the screen, you use the print command followed by what you want displayed after it – for example:
message = "hello"
This will display the contents of the variable message on the screen, which in this case is hello.
If, on the other hand, you enter the following code:
The word message will be displayed on the screen, because the speech marks tell Python to treat text within them as a string of characters and not a variable name.
print is slightly confusing in that it displays characters on the screen and has nothing to do with sending it to a printer to appear on paper.
To store multiple pieces of data in Python together, you can use lists. Lists are specified as items separated by commas within square brackets. Reconsidering the example of the cardboard box, a list can be considered as a named box with internal dividers to store separate items.
Looking back at the insult generator code, lists of strings are used to store multiple adjectives and nouns. Because you now know about strings and lists, you can try adding some more words of your own. Remember to enclose them in quotes (“”) and separate them with a comma.
A function can be thought of as a little machine that may take an input, perform some sort of processing on it and then produce an output (called its return value) as shown in Figure 2.7. You can create your own functions, or you can use functions that are included in Python or written by other people. To use a function, you call it by entering its name followed by ().
Figure 2-7: Functions are little machines that process inputs to produce an output.
Functions may take arguments (sometimes called parameters), which are a way of supplying data to them. Think of them as the raw materials into, or the controls that adjust, the function machine. Imagine a machine that makes different pasta shapes; its arguments might be raw pasta and a setting that determines what shape it produces. Arguments can be a variable (which may change as a program runs) or something hard-coded (written directly into the program by the programmer and never changed) in the program itself.
You can think of the print command that you used in the preceding code as a function that displays its parameter on the screen. The arguments to a function are contained in brackets after the function name.
Structuring Your Programs
Functions are a way to structure programs. Computers and computer programs can quickly become very complicated. The best way to deal with this is to break things down into simple, manageable chunks. It’s something we do in everyday life: If you ask someone to make you a cup of tea, you don’t give them a long list of instructions about filling the kettle with water, turning it on, waiting for it to boil, adding a tea bag to the teapot, and so on. We don’t think about all the details – after someone has been told how to make a cup of tea, they don’t need to be told all the steps each time. It's the equivalent of calling the makeTea() function – you need to define the steps only once. If you want to pass information like the number of sugars or milk to add to the tea, you might use arguments – for example, to specify tea with three sugars and milk, makeTea(3, True).
If we broke every task down to the simplest steps every time, things would become unmanageable. Programming computers is just the same – tasks are broken down into manageable chunks. Knowing exactly how and where to break a program into chunks comes with experience, but with this approach, it becomes possible to program a computer to make it do just about anything.
choice is another function that you have been using, perhaps without realising it. Its argument is a list of items, and the processing it does is to select one at random. Its output is an item from the list, which it returns.
If you find yourself writing the same code in multiple parts of a program, or using copy and paste, you should think about putting the repeated code into your own function.
There are so many functions that if all of them were available at once, it would be overwhelming to the programmer. Instead, Python contains only a few essential functions by default, and others have to be imported from packages of functions before they can be used. choice is an example of a function that needs to be imported from the random package. In the earlier example, the line import choice from random performs this role. You only need to import a function once in a program, but you can use it multiple times.
Insult Your Friends by Name!
The programs so far have produced an output, but when run, have not taken any input from the user. The next example asks the user for a name and then prints a personalised greeting. To try this out, enter the following code:
name = raw_input("What is your name?")
print ("Hello " + name)
raw_input became the input function in Python 3. If you’re using IDLE 3, remember to type input wherever you see raw_input in the examples in this book.
The raw_input function (renamed to input in Python 3) takes a message to print as its argument and returns the data the user entered. In this example, the variable name is assigned the result of the raw_input function, which is what the user types when the program is run.
This example also introduces how to join strings together. Strings are joined together, or concatenated as a programmer may say, by placing + between the strings. It’s important to note that because the computer treats strings as just characters and not words, when strings are concatenated, it does not automatically insert spaces. Therefore it is up to the programmer to add any spaces needed. In the preceding example, there is a space after Hello in the quotes – without this, the computer would print something like HelloFred.
Help with Functions
When you type a function like choice in IDLE, a tooltip pops up telling you what arguments the function takes and what it returns. This is a useful quick reference so you don’t have to remember exactly what parameters a function takes, and it’s easier than looking up the full reference online.
If you press the Ctrl key and the spacebar simultaneously, IDLE will attempt to autocomplete what you’ve typed thus far, which is useful if you can’t remember exactly what a function is called. To try this out, type pri and then press Ctrl + spacebar. You should see a list of functions with print highlighted, as shown in Figure 2.8. Press the spacebar again to have IDLE finish off the typing for you.
Figure 2.8: Autocomplete of the print function in IDLE.
Computer programs would be very dull if they always executed the same statements. Luckily, programs can do different things depending on these conditional tests: equal (==), not equal (!=), less than (<), greater than (>), less than or equal (<=) and greater than or equal (>=).
In this example, you’ll make your insult generator change what it prints depending on the age of the user. To achieve this conditional behaviour, you’ll tell the program to do one thing if something is true, or if not true, do something else. As a quick test of conditional behaviour enter the following code in an empty file:
age = 12
if (age < 16):
Run the program and you should find it prints young. Change the age variable to be larger than 15 and run the program again. This time it should print old.
Note that these print statements are indented by typically four spaces or a tab from the beginning of the line. Unlike some other languages, indentation matters in Python. If you don't get spaces in the right place, either Python gets confused and raises an error, or your program won't do what you expect! You should always indent code properly.
Create a Stream of Insults!
In the next part of this project, you’re going to change the program to produce multiple insults, which is a good example of the use of functions. You’re going to define your own function that you can call whenever you want an insult, and then create a loop that calls the function multiple times.
Making Your Own Functions
You define functions in Python by writing def (for definition) followed by the name of the function and the parameters it takes and a colon (:), followed by the indented body of the function.
As a simple example, enter the following in an interactive Python window to define a simple function that will print a personalised greeting:
def printHelloUser (username):
print ("Hello " + username)
Note that the body of the code is indented. This shows that it is still part of the function on the previous line. Also note that there are no spaces in the function names. Including spaces would confuse the computer, so programmers separate words by using capitals in the middle (likeprintHelloUser in the example). Some programmers call this camel case because the capital letters in the middle of a word are like humps on the back of a camel.
Python doesn’t care what you call your functions, but other programmers will! So if you want other people to use your code, you should follow conventions.
Now enter the following to call the function you just defined:
You’re now ready to use what you’ve learned in this chapter to write a printInsult function. To begin, enter the following code in an interactive Python window, remembering the indentation:
from random import choice
def printInsult (username, age):
adjectives = ["wet", "big"]
nouns = ["turnip", "dog"]
if (age < 16):
ageAdjective = "young "
ageAdjective = "old "
print (username + ", you are a " +
ageAdjective + choice(adjectives) +
" " + choice(nouns))
Now, whenever you need a personalised insult you can just call printInsult, with your victim’s name and their age, and it will produce one on demand! So, to insult 10-year-old Fred, you would write the following code line:
And Python would print something like this:
Fred, you are a young wet turnip
Call the printInsult function with the names and ages of some of your friends and family!
Loops are great when there’s repetition in a task. To try this out, you’re going to create a program that loops around a few times, each one producing another insult. You’ll look at two variations of loops: a for loop and while loop. Both have a test that determines if the code in the loop body should be run again, or if the program should skip the loop body and continue. A for loop is typically used as a counting loop, where code needs to be run for a particular number of times – for example, for six times. A while loop tends to be used while a condition is true – for example, while a user wants to continue running the program.
Type the following code to loop for each item in the adjectives list and print it out:
adjectives = ["wet", "big"]
for item in adjectives:
The indented code, print (item), is the body of the loop that is repeated on each iteration (loop). for item in adjectives: sets up the loop and tells Python to loop for each item in the adjectives variable. On each iteration, the next value from the list is placed in the item variable.
So, to print “hello world” three times you write this:
for count in [1, 2, 3]:
print ("loop number ",count)
print ("hello world")
You can use commas to separate multiple items for printing.
You can use range instead of typing every number in a list. Type
In Python 2 range returns a list. In Python 3 you need to tell it specifically when you want it to return a list – this is not necessary within a for statement.
Python returns the list of numbers from 0 to 9:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You can also give range two arguments – a start and an end – like this:
You will use a for loop with a range to test the printInsult function. In the same interactive Python window where you defined printInsult(), enter the following code:
for testAge in range (14,18):
print ("age: " + str(testAge)
Python prints the following:
Monty, you are a young big turnip
Monty, you are a young big dog
Monty, you are a old big dog
Monty, you are a old wet dog
Let’s look at an example while loop. Type the following code and run it. It will loop and keep printing an insult until you type no.
userAnswer = raw_input("can you take any more?")
!= means not equal, so the while loop repeats whilst the variable userAnswer is not equal to no. After printing an insult the code gets input from the user and updates the userAnswer variable ready for the test before the start of the next loop.
raw_input was renamed input in Python 3.
Consider what the loop would look like if you didn’t create a function – you’d have to include all the code inside the loop body. This makes the code harder to read, and means you’d have to retype it in each of these examples!
If your program gets stuck in an infinite loop, a loop that never ends, you can stop your program by pressing Ctrl + C.
Putting It All Together
You should now have a program that generates a torrent of insults! This chapter has covered the basics of programming in Python. Look at each line in the examples and see if you understand what each part does. Then, to personalise your program, you could make it produce different insults depending on the user’s name. For example, you could make it say something nice only if your name is entered, or you could change the number of insults it generates depending on the user or their age (such as a younger brother). You could print “really old” for people over a certain age, or if you’re clever¸ you could use a loop to print an additional “really ” for every decade someone has been alive.
The main thing is to not be afraid of changing things to see what happens. Just as you can’t learn to paint without practising, you won’t learn how to program without experimenting. Throughout this book, there are ideas to change the projects to make them your own and to make the computer do what you want it to do.