Lesson 3

Conditional statements

In our programs so far we have only covered sequences and looped sequences. When we want our program to do something different depending on its environment, we need to use conditionals.

A conditional statement allows us to test if something is true, and if it is then do something different. This example does 3 different things depending on what the variable loops is set to.

1
2
3
4
5
6
if loops == 3:
    pencolor("red")
elif loops > 10:
    pencolor("green")
else:
    pencolor("blue")

We have these to choose from:

More turtle codes

Colour mixing

We've been using primary colours so far by calling their names, like pencolor("red"). It's also possible to mix up our own colours like this:

pencolor(0.5,0.3,0.1)

The 3 arguments stand for the red, green and blue parts of the colour mix. So in the example above we've set the red value to 0.5. They can be set to anything between 0 and 1. If the value ever becomes more than 1 you will get an error.

How could you make the colours change as your program progresses?

Filling

We can fill areas by starting a fill, moving the turtle, then ending the fill. The main functions for filling are:

Here's an example for a filled triangle:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from turtle import *
fillcolor("blue")

#start the fill
begin_fill()

#draw a shape
forward(100)
left(90)
forward(100)

#end it
end_fill()

done()

Stamping

We can also make shapes by stamping, like a stamp and ink pad. The two main functions for this are:

Here's an example of changing the shape to a square and stamping it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from turtle import *

fillcolor("yellow")
shape("square")
loops = 0

while loops < 60:
    stamp()
    forward(30)
    #turn left a little bit more each time
    left(loops)
    #increment loop counter
    loops = loops + 1

done()

You can find out which shapes are available for stamping here

Enter your code to win a Raspberry Pi!

Put your name, class, school and teacher's email at the top of your entry using comments:

# Alice and Bob
# class 11a
# Pickwick High School
# Mrs.Smith@pickwick.sch.uk

Then email your code to us at entries@turtleprize.com. We'll let your teacher know if you've won!