Learning Python® with Raspberry Pi®

Chapter 1

Getting Up and Running

WELCOME TO Learning Python with Raspberry Pi. In this book, you'll learn how to unlock the full power of the tiny computer, from 3D graphics to games programming to controlling electronics to tweeting. You'll see what's going on under the hood and learn how to create programs that take advantage of every feature of this minuscule computer.

Setting Up Your Raspberry Pi

To follow this book, you'll need a few bits of equipment:

  • Raspberry Pi
  • USB keyboard
  • USB mouse
  • SD card
  • Monitor
  • Power supply

There are also a few optional bits of kit that may help:

  • Powered USB hub (highly recommended)
  • Camera module
  • USB webcam
  • USB WiFi dongle

It is possible to do everything in this book with a model A Raspberry Pi. The real advantage of a model B as far as programming is concerned is the network port. This port will make it easier to connect to the Internet, which you'll need to do to install some software.

Any USB keyboard and mouse should work fine. Most SD cards should work, although there are a few that will cause problems. If you're unsure, buy one from a Raspberry Pi online shop (there are links to a few on http://raspberrypi.org).

The Raspberry Pi has a HDMI (high-definition multimedia interface) video output, but most monitors have VGA or DVI input. If at all possible, use a monitor that has DVI or HDMI input. A HDMI-to-DVI converter should cost only a few pounds/dollars and shouldn't detract from the image quality. HDMI-to-VGA converters are available, but they're more expensive and can cause problems, so use them only if you have no other option.

Most micro USB power supplies from reputable manufacturers should work; however, some cheap ones from no-name companies have caused problems, so if possible, don't skimp too much on this. You could use a USB cable from a normal computer to power your Pi.

Powered USB hubs are recommended for the power-related problems described later in this chapter. Not all USB hubs are powered, so make sure that whatever one you get plugs into the mains electricity to get extra power.

We talk more about camera options in Chapter 9 on multimedia. The only thing to say here is that if you do choose to get a USB webcam, make sure it's compatible with the Raspberry Pi. There's a partial list of working web cams at http://elinux.org/RPi_USB_Webcams.

You'll need to connect your Pi to the Internet to install the software you need in this book. You can do this either by plugging your Pi into your router with a network cable or by using a USB wireless dongle, which will add WiFi connectivity.

Solving Problems

The most common problems with the Raspberry Pi are power-related issues. Not all micro USB power sources can provide enough power, and it becomes more of a problem as you connect peripherals to your Pi, or when you overclock it (see Chapter 5 for more details). Power-related problems will usually manifest themselves as the computer crashing, so if you find that your Pi becomes unstable, this is the best place to start. A good way to get around such issues is to connect your Pi to one power source and connect all the peripherals (keyboard, mouse, and so on) via a powered USB hub.

The second most common cause of problems with Pis is the SD card. These issues can be caused by power supply problems, or they can be problems with the cards themselves. It's important to take preventative measures here to ensure that your data is safe, and that means backups! You can use a service such as Google Drive (although this runs slowly on the Pi), or you can simply keep extra copies of any work on a USB memory stick. SD card issues will usually manifest themselves by the Pi displaying error messages when you try to start it. Most of the time you can solve the problem by reinstalling Raspbian, but if this doesn't work, you'll need to get a new SD card.

If neither of these help, then you'll need to dig a little deeper. The most useful places to look are the kernel buffer and the system log file. The kernel buffer is usually best if you're having problems with hardware, such as a USB device not working. If you open LXTerminal and type:

dmesg

It will output all the messages from the Linux Kernel. The last ones are the most recent and should show any problems.

The system log file (often called syslog) can be displayed with:

cat /var/log/syslog

Again, the most recent messages will be at the end. The information in both of these can be somewhat cryptic. If you still can't work out the problem after reading these, the best place to go is the Raspberry Pi forums at www.raspberrypi.org/phpBB3/. There's a community of helpful people who should be able to point you in the right direction.

A Quick Tour of Raspbian

This is a book about programming, not about generally using Raspbian, so we won't dwell on it too much, but you'll find it useful to know a bit about what's going on.

There are a few operating systems available for the Raspberry Pi, but the instructions in this book are all based on Raspbian, which is the default operating system, and the best choice for a new user. If you have some experience with Linux, you could use Arch or Fedora if you like, but you'll have to change the apt-get commands to ones suitable for your package manager.

The easiest way to install Raspbian on your Pi is using NOOBS, which is available from www.raspberrypi.org/downloads. You'll also find a quick start guide at that website that will tell you everything you need to know to get up and running.

There are two different ways of interacting with Raspbian—from the terminal and using the graphical system (LXDE).

Using LXDE (Lightweight X11 Desktop Environment)

The Lightweight X11 Desktop Environment is the standard windowing system for Raspbian. Its basic setup is the same as most versions of Windows pre-Windows 8. There's a button in the bottom-left side of the screen that opens an applications menu, and currently running applications are displayed in the bar along the bottom (see Figure 1-1).

Figure 1-1: The LXDE desktop with the menu open.

If you get a black screen with white text asking you to log in when you boot up your Pi, it means that you haven't set it up to start LXDE automatically. Don't worry; just log in with the username pi and the password raspberry, and then type the following:

startx

You can set it up to boot into LXDE automatically using raspi-config (see the next section).

Using the Terminal

LXDE is great for many tasks, but sometimes you'll need to use the command line. This is an incredibly powerful interface that's accessed through the terminal. In LXDE, that means opening the LXTerminal application.

When you open LXTerminal, you should see the following line:

pi@raspberrypi~$

This signifies that you are using the username pi on a computer called raspberrypi, and you are in a directory called ~.

In Linux, all directories start from / or root. This is the base of the directory tree and every directory is located in some subdirectory of this. You can move between directories using the cd (change directory) command. Start by moving to this root directory with:

cd /

You should now seen that the command prompt has changed to

pi@raspberrypi/$

You can list the contents of this directory with the command ls. One of the subdirectories is called home. This is where every user on the system has his home directory. Move into it and view its contents with:

cd home
ls

There should only be one directory called pi. The command prompt should now have changed to show that you're in the directory /home. Move into the only subdirectory with:

cd pi

Now the command prompt will have reverted to:

pi@raspberrypi~$

This is because the character ~ is a shorthand for the current user's home directory. When you type ~ in the terminal, the computer converts it to /home/pi.

There is much more to learn about the command line. So much so that it would take another book this size to cover it with any semblance of completeness. However, you don't need to know everything to start using it, and whenever we tell you to use LXTerminal, we tell you exactly what to type.

We'll leave you with two pieces of advice. Firstly, don't be afraid of the terminal. It can be a bit daunting at first, but the only way to learn how to use it is to use it. Secondly, almost all commands have built-in help that you can access using the flag ––help. For example, if you want to learn more about how to use the command ls, you can enter:

ls --help

This will output:

Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by
default). Sort entries alphabetically if none of -cftuvSUX nor
--sort is specified.

It then goes on to list all the various flags you can use with the command.

Changing Configurations with Raspi-Config

Raspbian comes with a tool to help you set up the hardware on your Raspberry Pi; it's called raspi-config. To start it, open LXTerminal and type:

sudo raspi-config

Here, you'll find options to start LXDE automatically when you boot up, overclock your Pi, and other things. Overclocking your Pi will make a few things in this book run a little better, most notably, installing new software.

Installing Software

You can install new software on your Raspberry Pi using the apt-get command in the terminal. Before installing anything, it's a good idea to update all your software to the latest version. You can do this with:

sudo apt-get update
sudo apt-get upgrade

Then you can use apt-get to install whatever you want. For example, if you want to use iceweasel (a re-branded version of Firefox), you need to open LXTerminal and type:

sudo apt-get install iceweasel

If you prefer to do this using a graphical program, you can get the program synaptic with:

sudo apt-get install synaptic

When you want to install something, you can start it with:

sudo synaptic

From there you'll be able to search for whatever you want.

Python 3

In this book, you'll learn how to use the Python 3 programming language. In Raspbian, there are a couple of ways to use this language.

The Python Interpreter

There are two ways of using Python, from the shell and saved programs. The shell executes each instruction as you type it, which means it's a really good way of trying out things and doing experiments. Saved programs are bits of Python code that are saved in a text file and run all at once. It's easy to tell which environment you're in because in the shell, all the lines will start with three chevrons:

>>>

Most of the time in this book, we'll deal with saved programs, but there are some occasions (particularly early on) when we tell you to use the shell. To make it clear which bits of code are for which, we've started every bit of code for the shell with three chevrons.

Running Python Programs

There are two different ways you can write programs for Python. You can create text files that contain the code, and then run these files with Python, or you can use an Integrated Development Environment (IDE) such as IDLE 3. Either way will result in the code being run in the same way and it's just a matter of personal preference.

If you want to write the programs as text files, you need to use a text editor such as Leafpad. A word processor such as LibreOffice's Writer is unsuitable because the various formatting it uses will confuse Python. As an example, open Leafpad and create a new file that just has the line:

print("Hello World!")

Once you've created your file, just save it with the extension .py; for example testfile.py. You can then run it by opening LXTerminal and navigating to where the file is saved. Then you run python <filename>. You can use the cd command to move to different directories. For example, if you save the file in a folder called programming in your home directory, you could run it by typing the following into LXTerminal:

cd programming
python3 testfile.py

If everything has worked correctly, you should see the following line appear on the screen:

Hello World!

The second way is a little simpler. Using an IDE, the text editor and Python interpreter are in the same program. For example, open IDLE 3 (make sure to use the one with the 3), and go to File⇒New Window. In the new window, enter this code:

print("Hello IDLE")

Then go to Run⇒Run Module. It will prompt you to save the module, so select a filename. Once you've done this, it will switch back to the Python interpreter and display the following:

Hello IDLE

It doesn't really matter which one you use, so just go with the way you feel most comfortable with.

Summary

After reading this chapter, you should understand the following a bit better:

  • You'll need a few extra bits of hardware to get the most out of your Raspberry Pi.
  • Insufficient power is the most common cause of problems.
  • If you're having problems, dmesg and syslog are the best places to find out what's going on.
  • Raspbian uses the LXDE desktop environment.
  • The terminal provides the most powerful way of interacting with the underlying operating system.
  • The raspi-config tool lets you configure your Raspberry Pi.
  • Use apt-get to install new software.
  • You can run Python either through the interpreter or by running saved programs.

Chapter 2

A Really Quick Introduction to Python

IN THIS CHAPTER, you'll dive right into some code examples. Don't expect to grasp all the details yet. This chapter is meant to give you a taste of programming. You'll learn how to draw on the screen, and even how to make a simple game. Along the way you'll pick up some basic programming concepts, but don't worry if you don't understand every line of every program you create in this chapter. You'll learn more about the details in later chapters.

Drawing Picture with Turtles

It's time to get programming! We strongly recommend that you enter the code into IDLE 3 as you read along, as it will help you understand what's happening. So, without further ado, open IDLE 3, go to File⇒New Window, and enter the following:

import turtle
window = turtle.Screen()
babbage = turtle.Turtle()
babbage.left(90)
babbage.forward(100)
babbage.right(90)
babbage.circle(10)
window.exitonclick()

Then go to Run⇒Run Module or press F5 to execute the program. A dialog will open and ask you to provide a filename. This name can be whatever you want, although it helps if it's descriptive so you'll remember it in the future (we used chapter2-example1.py).

Each of these lines is an instruction to Python. Python goes through them one-by-one and executes them in the order it finds them. The result of the computer following all these steps is to draw a line with a circle on top, as shown in Figure 2-1. You might think the drawing looks like a lollipop, but actually, it's the first part of a flower. If you don't get this result, go back and check that everything is typed correctly and try again.

Figure 2-1: Your first turtle drawing with Python.

Let's take a closer look at what Python's doing as it goes through the code.

import turtle

You'll often see several import lines at the start of Python programs. They bring extra features into programs a bit like add-ons or plug-ins in other software. These features are grouped into modules. You'll learn more about how to use the import command in the following chapter. This time we're importing the turtle module, which lets us draw graphics.

The next portion of the code is

window = turtle.Screen()
...
window.exitonclick()

This creates a new window that we can draw onto, and set it to close when it's clicked.

The next line uses the turtle module that you imported in the first line to create a new turtle, named babbage (after Charles Babbage, who invented the concept of the computer):

babbage = turtle.Turtle()

Babbage has a number of methods, or things you can tell it to do. For example, in the line:

babbage.left(90)

You're using the method left() which turns babbage left a certain number of degrees. Parameters are added in the brackets after the method and you can use them to send certain bits of information to control how the method runs. In this case, you passed the parameter 90, so babbage turns left 90 degrees. The following lines use the methods forward(), right(), and circle().

babbage.forward(100)
babbage.right(90)
babbage.circle(10)

The first method moves the turtle forwards 100 pixels, the second turns it right 90 degrees, and the final one draws a circle with a radius of 10 pixels.

Now it's time to add a petal. Edit the code so that it reads as follows (changes are in bold):

import turtle
#create window and turtle
window = turtle.Screen()
babbage = turtle.Turtle()
#draw stem and centre
babbage.left(90)
babbage.forward(100)
babbage.right(90)
babbage.circle(10)
#draw first petal
babbage.left(15)
babbage.forward(50)
babbage.left(157)
babbage.forward(50)
#tidy up window
window.exitonclick()

Run this now. You should see that the flower now has a solitary petal. You'll notice that we've added some lines that begin with a # symbol. The computer ignores any line that starts like this, so you use them to leave little comments to yourself (or anyone else who looks at the code). These make the code more readable, and mean that if you come back to the code in a few days, weeks, or even years, you can easily see what it's doing.

Using Loops

You should find the section that draws the petal quite easy to understand (we calculated the angles of the two left turns using trigonometry, but don't worry, we won't be going into the maths here).

You could now add a block of code to draw a second petal (there'll be 24 in total). It will be exactly the same as the first petal, and directly below it, so with a bit of copy and paste, you'll get the following:

#draw second petal
babbage.left(15)
babbage.forward(50)
babbage.left(157)
babbage.forward(50)

And then do the same for the next 22 petals … Okay, hang on here. As a general rule of thumb, when programming, you should never repeat identical code. Suppose you decided to change the size of the petal; you'd have to change it 48 times (twice for each petal), and if you forgot any one, you'd get a wonky picture. Instead, you can use a loop, which is a piece of code that tells the computer to repeat a certain section of code over and over again.

Instead you can replace all the code from #draw first petal downwards with the following code:

#draw all petals
for i in range(1,24):
    babbage.left(15)
    babbage.forward(50)
    babbage.left(157)
    babbage.forward(50)
window.exitonclick()

We'll deal with exactly what the first line (after the comment) means in the next chapter, but for now, it's enough to say that it repeats the block 24 times, then the computer moves on to the instructions after this block.

Code blocks like loops (and others that you'll explore later) always follow the same layout in Python. The first line ends with a colon, and every line after it is indented. Once the tabbing/indention stops, Python considers this code block over. If you've programmed in other languages before, you'll probably have noticed that they do things a little differently.

Try running the code. You should find that babbage runs round drawing all the petals, and we finish with a complete flower, as shown in Figure 2-2.

Figure 2-2: Loops make drawing flowers a breeze.

Not bad for just 13 lines of code! Of course, not many flowers are all black, so it would be better if you could add a little colour to the picture. The Python turtle module does include some methods that allow you to change the colour of your drawing. Amend the first half of your program so it reads as follows (changes are shown in bold):

import turtle
#create window and turtle
window = turtle.Screen()
babbage = turtle.Turtle()
#draw stem
babbage.color("green", "black")
babbage.left(90)
babbage.forward(100)
babbage.right(90)
#draw centre
babbage.color("black", "black")
babbage.begin_fill()
babbage.circle(10)
babbage.end_fill()

As you can see, we're using the color(colour1, colour2) method (Brits should notice the American spelling of the method), where colour1 is the pen colour and colour2 is the fill colour. When you start the centre circle of the flower, you tell the computer to fill in the circle with the begin_fill() method. Afterwards, we used end_fill() so it doesn't keep filling in all the petals.

Conditionals: if, elif, and else

Now type the second half of the flower-drawing program into IDLE 3:

#draw all petals
for i in range(1,24):
  if babbage.color() == ("red", "black"):
     babbage.color("orange", "black")
  elif babbage.color() == ("orange", "black"):
     babbage.color("yellow", "black")
  else:
     babbage.color("red","black"))
  babbage.left(15)
  babbage.forward(50)
  babbage.left(157)
  babbage.forward(50)
#hide the turtle
babbage.hideturtle()
#tidy up window
window.exitonclick()

We've used a little artistic licence and decided that the flower should have petals with three different colours: red, orange, and yellow. As this book is in black and white, you'll have to run the program on your Raspberry Pi, or you can take a look at flower.png on the companion website, to see the result in living color. To alternate our petal colours, we've used an if .. elif .. else block. This is a way of telling Python how to make decisions about what to do based on certain data. The basic structure is as follows:

if <condition> :
    code

where <condition> is a statement that can be true or false. In this case, we're using the following condition:

babbage.color() == ("red", "black")

babbage.color() (note that now this method doesn't have any parameters) tells the program what colour our turtle currently has. This is a little different to the methods you've seen so far because it sends information back that you can use. This return value is a pair of colours—the first is the drawing colour, and the second is the fill colour (which hasn't changed since you set it to draw the centre of the flower, so it will stay the same for the whole of the program). The double equals sign (==) means ‘is equal to’. You use a double equals here because a single equals is used differently, like when you created the window and the turtle.

If the condition is true (in this case, if the turtle's colour is (“red”, ”black”)), then Python executes the code. However, if the condition is false, Python moves on to the elif (elif is short for else if ). This has the same structure as the original if condition.

If the condition in the elif is false, then Python moves on to the else. If it gets this far (that is, if the conditions for the if and elif are both false), Python will execute the code. else doesn't have a condition. Figure 2-3 shows the flow of this logic.

Figure 2-3: The flow of conditional logic for determining the colour of each flower petal.

This if clause then, will alternate the colour of the pen after each petal is drawn. The final alteration is to add the following line to the end of the program:

babbage.hideturtle()

This simply makes the turtle (cursor) invisible so it doesn't obscure our picture. There you have it; your very first Python program finished completely!

Using Functions and Methods to Structure Code

Before we dive in and start our second Python program, we're going to pause for a second to talk a bit more about methods. As you've seen, methods are really useful for controlling parts of our program. In the previous example, you used them to move turtles, change colour, and create windows. Each time, you called them on something. For example, you called forward(50) on babbage with babbage.forward(50) and exitonclick() on window with window.exitonclick(). Each time, the methods run bits of code that are stored in the Python modules. Python has another similar feature called functions. These work in a fairly similar way, but they're not called on anything. For example, in your Python interpreter, type:

>>> print("Hello World")

This runs the print() function that simply outputs its parameter to the screen. Remember when we said that you shouldn't repeat any code in your programs? We explained that loops are one way of reducing repetition, and functions are another. As an example, think of a program that deals with circles and often needs to calculate the area for a given radius. If you listened in maths classes, you should know that the area of a circle is 2 × pi × the radius (if you didn't listen in maths class, then you'll just have to take our word for it). Rather than repeat this every time you need to calculate the area of a circle, which could lead to problems (if you mistype the value of pi somewhere, it could cause all sorts of problems and be hard to find), you can create a function to do it. In Python this would be:

def circlearea(radius):
    return radius * 3.14 * 2

print(circlearea(1))

Here we've used two functions nested together. circlearea(1) calculates the area of a circle with a radius of one, and print() sends this number to the screen.

As you can see, you define your own functions using the word def, followed by the name of the function, followed by the parameters enclosed in brackets. You can then use the name of the parameter inside the function where it will act with the value that's passed to it. The word return tells Python what value you want to send back. So, in the previous example, when Python gets to the phrase circlearea(1), it runs the code under def circlearea(radius), but instead of radius it substitutes the number you passed across (1). Then it returns the value of that calculation (6.28) to the print function. You'll see later that you can nest methods in the same way so that one method sends information straight to another one. This can be a really useful way of getting data to flow in the right way between different sections of your program.

A Python Game of Cat and Mouse

Now, let's move on to our second Python program. This time you're going to make a game of cat and mouse. The player will control the mouse using the arrow keys, and she has to stay ahead of the cat (controlled by the computer). The longer she stays ahead, the higher score she gets.

Open a new window in IDLE 3 and type the following code:

import turtle
import time


boxsize = 200
caught = False
score = 0

#functions that are called on keypresses
def up():
 mouse.forward(10)
 checkbound()


def left():
 mouse.left(45)

def right():
 mouse.right(45)

def back():
 mouse.backward(10)
 checkbound()


def quitTurtles():
 window.bye()

#stop the mouse from leaving the square set by box size
def checkbound():
 global boxsize
 if mouse.xcor() > boxsize:
     mouse.goto(boxsize, mouse.ycor())
 if mouse.xcor() < -boxsize:
     mouse.goto(-boxsize, mouse.ycor())
 if mouse.ycor() > boxsize:
     mouse.goto(mouse.xcor(), boxsize)
 if mouse.ycor() < -boxsize:
     mouse.goto(mouse.xcor(), -boxsize)

#set up screen
window = turtle.Screen()
mouse = turtle.Turtle()
cat = turtle.Turtle()
mouse.penup()
mouse.penup()
mouse.goto(100,100)

#add key listeners
window.onkeypress(up, "Up")
window.onkeypress(left, "Left")
window.onkeypress(right, "Right")
window.onkeypress(back, "Down")
window.onkeypress(quitTurtles, "Escape")


difficulty = window.numinput("Difficulty",
   "Enter a difficulty from easy (1), for hard (5) ",
   minval=1, maxval=5)

window.listen()
#main loop
#note how it changes with difficulty
while not caught:
 cat.setheading(cat.towards(mouse))
 cat.forward(8+difficulty)
 score = score + 1
 if cat.distance(mouse) < 5:
     caught = True
 time.sleep(0.2-(0.01*difficulty))
window.textinput("GAME OVER", "Well done. You scored:
    "+ str(score*difficulty))
window.bye()

That's quite a lot of code, but before you look at it too deeply, play the game a few times to get a feel for it. This will also help you make sure that you've entered it correctly. If you get any errors, check your typing, and then try again. Take a look at Figure 2-4 to see it in action.

Figure 2-4: A simple game of cat and mouse.

Understanding Variables

The first two lines just bring in modules for using turtles and time, and then the following three lines are

boxsize = 200
caught = False
score = 0

These lines use something that we've touched on, but haven't really talked about: variables. Variables are places where you can store values you want to use later. For example, in the first line, you store the value 200 in the variable boxsize. After you've set them up like this, you can simply put in boxsize and Python will substitute the correct value. These constructs are called variables because they can change. In this particular program, boxsize will stay the same, but both caught and score will vary throughout it. Each time you want a new value, you simply use the single equals sign. This is the same thing you did in the first example with window and babbage; there the variables held the screen and the turtle. We'll cover variables, and what exactly you can store in them in the next chapter.

Defining Functions

The next part of the code defines some functions that you'll use in the program. In the function checkbounds(), you'll notice that there's the following line:

global boxsize

This line is needed because functions don't automatically get access to variables defined outside of them. This line tells Python that we want to use the boxsize variable in this function, and it's declared outside of the function itself.

Perhaps the most confusing section is

#add key listeners
window.onkeypress(up, "Up")
window.onkeypress(left, "Left")
window.onkeypress(right, "Right")
window.onkeypress(back, "Down")
window.onkeypress(quitTurtles, "Escape")

This code tells the window what to do when various keys are pressed. For example, the first line says to run the function up (which we've already defined) whenever the key “Up” (which corresponds to the up arrow on the keyboard) is pressed.

Looping Through the Game

Next you get to the main loop that runs the game:

while not caught:
 cat.setheading(cat.towards(mouse))
 cat.forward(8+difficulty)
 score = score + 1
 if cat.distance(mouse) < 5:
     caught = True
 time.sleep(0.2-(0.01*difficulty))

This code uses a different type of loop. The while loop take this form:

while condition:
  loop code

They keep on looping the code as long as the condition is True. In the initial list of variables at the beginning of the code, you set the variable caught to False:

caught = False

Thus in this case, not caught is the condition (and it's true at the start since not False is True), so the program keeps running until you change it to true because not True is False. It all sounds a bit complex when phrased like this, but an easy way to think of it is that the word not just swaps True and False around.

time.sleep() tells Python to stop for a certain number of seconds. In this case you reduce the amount of time it sleeps as the difficulty level (which is a variable set to a number that the user enters) increases. You should also be able to see that the distance the cat moves increases with difficulty.

Summary

This brings us to the end of our really quick tour of Python. Hopefully the programs made some sense to you. Don't worry if you didn't understand a hundred percent of everything, because we're going to look at the different parts of Python in a bit more detail in the next chapter. However, hopefully you now understand the following:

  • Python programs consist of a series of instructions and they run from top to bottom.
  • You can control the way Python moves through your program using loops and if statements.
  • You don't have to do everything yourself. You can import modules and use methods to take care of much of the work.
  • Functions allow you to reuse code, which makes your programs easier to understand and maintain.
  • Variables allow you to store information so you can use it later.
  • It's really easy to draw flowers and make games in Python.

Remember, when programming there's often more than one way to do something, and if you can pick the right way (or at least, not the wrong way) you'll make your life easier. However, it's not always easy to know if a way is right or wrong, so we'll finish this chapter with Python's own advice on the matter. In your Python interpreter, type:

>>> import this

this is a special module that outputs some useful Python advice when it's imported. Now that you have a feel for Python, let's move on and dig into the code a bit deeper.