The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

102 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


Project 1: Turtle Snowflakes
Now you understand how Python works, it’s time to play with graphics and create a snowflake
using a tool known as a turtle.

Originally physical robots shaped like their animal namesakes, turtles are designed to move
in a straight line, turn, and to lift and lower a pen – in the digital version, simply meaning to start
or stop drawing a line as it moves. Unlike some other languages, namely Logo and its many
variants, Python doesn’t have a turtle tool built into it – but it comes with a library of add-on code
to give it turtle power. Libraries are bundles of code which add new instructions to expand the
capabilities of Python, and are brought into your own programs using an import command.
Create a new program by clicking on the New icon, and type the following:

import turtle

When using instructions included in a library, you have to use the library name followed by
a full stop, then the instruction name. That can be annoying to type out every time, so you can
assign a shorter variable name instead – it could be just one letter, but we thought it might be
nice for it to double as a pet name for the turtle. Type the following:

pat = turtle.Turtle()

To test your program out, you’ll need to give your turtle something to do. Type:

pat.forward( 100 )

Click the Run icon, and save your program as Turtle Snowflakes. When the program has
saved, a new window called ‘Turtle Graphics’ will appear and you’ll see the result of your
program: your turtle, Pat, will move forwards 100 units, drawing a straight line (Figure 5-8).

CHALLENGE: ADD MORE QUESTIONS
Can you change the program to ask more than one
question, storing the answers in multiple variables?
Can you make a program which uses conditionals and
comparison operators to print whether a number typed in
by the user is higher or lower than 5, like the program you
created in Chapter 4, Programming with Scratch?

ONLINE PROJECT
This project is also available online at rpf.io/turtle-snowflakes
Free download pdf