The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 5 Programming with Python 105

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


While a robotic turtle draws in a single colour on a large piece of paper, Python’s simulated
turtle can use a range of colours. Add a new line 3 and 4, pushing the existing lines down:


turtle.Screen().bgcolor("blue")
pat.color("cyan")

Run your program again and you’ll see the effect of your new code: the background colour of the
Turtle Graphics window has changed to blue, and the snowflake is now cyan (Figure 5-11).


5 Figure 5-11: Changing the background and snowflake colours


You can also have the colours chosen randomly from a list, using the random library. Go
back to the top of your program and insert the following as line 2:


import random

Change the background colour in what is now line 4 from ‘blue’ to ‘grey’, then create a new
variable called ‘colours’ by inserting a new line 5:


colours = ["cyan", "purple", "white", "blue"]

U.S. SPELLINGS
Many programming languages use American English spellings, and
Python is no exception: the command for changing the colour of
the turtle’s pen is spelled color, and if you spell it the British English
way as colour it simply won’t work. Variables, though, can have any
spelling you like – which is why you’re able to call your new variable
colours and have Python understand.
Free download pdf