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.

9781118717059-fg0201.tif

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.

9781118717059-fg0202.tif

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.

9781118717059-fg0203.tif

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.

9781118717059-fg0204.tif

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset