The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

106 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


This type of variable is known as a list, and is marked by square brackets. In this case, the list is
filled with possible colours for the snowflake segments – but you still need to tell Python to choose
one each time the loop repeats. At the very end of the program, enter the following – making sure
it’s indented with four spaces so it forms part of the outer loop, just like the line above it:

pat.color(random.choice(colours))

Click the Run icon and the snowflake-stroke-ninja-star will be drawn again. This time,
though, Python will choose a random colour from your list as it draws each petal – giving the
snowflake a pleasing, multicolour finish (Figure 5-12).

5 Figure 5-12: Using random colours for the ‘petals’

To make the snowflake look less like a ninja star and more like an actual snowflake, add a
new line 6, directly below your colours list, and type the following:

pat.penup()
pat.forward( 90 )
pat.left( 45 )
pat.pendown()

The penup and pendown instructions would move a physical pen off and on to the paper
if using a turtle robot, but in the virtual world simply tell your turtle to stop and start drawing
lines. This time though, rather than using a loop, you’re going to be creating a function – a
segment of code which you can call at any time, like creating your very own Python instruction.
Free download pdf