# Data Warehousing and Data Science

## 10 September 2020

### Turtle

Filed under: Python — Vincent Rainardi @ 5:07 am

My son asked me to show graphics in programming and I thought it would be a good idea to show Turtle. In Python of course, as it is the most popular programming language, serving all kinds of communities not just AI. Turtle is a simple way to draw lines and circles. And it’s already built in Python, i.e. you don’t need to install anything.

To start with just type “import turtle”. This is to import the turtle library into python environment.

Then type “t = turtle.Turtle()”. This is to create a variable t so that we don’t have to type turtle.Turtle many many times. It opens a window like this with an arrow facing to the right. That arrow is the cursor. That window is our canvas, where we make our drawing.

To draw a line, type “t.forward(50)”. This is to move the arrow 50 pixel forward (to the right).

To change the same of the cursor, type “t.shape(“turtle”)”:

To draw a circle, type “t.circle(50)”:

To turn the turtle to the right 90 degrees, type “t.right(90)”:

And you can do “t.forward(50)” to draw a line again:

To lift the pen up so it won’t make any line, type “t.penup()”. Now we can move the turtle without drawing anything, for example: “t.setposition(0,-50)” like this:

(0,0) is where we began. It’s x,y so 0,-50 means the x is 0 and the y is -50 (50 down).

50,0 means x = 50 and y = 0, like below:

Remember that our pen is still up at the moment. To start drawing again, let’s put the pen down by typing “t.pendown()”. We can draw a circle again: “t.circle(25)”, like below left:

To undo what we did last, type “t.undo()”, like above right.

To fill with colour, type this:

• t.fillcolor(“green”)
• t.begin_fill()
• t.circle(25)
• t.end_fill()

And finally, to clear the screen, type: “t.clear()”.

As an example, to make a square, it is like below. We use a “for” loop.

``````for _ in range(4): {shift-enter}
t.forward(25) {shift-enter}
t.right(90) {enter 2x}
``````

Another example: a filled hexagon.

``````t.fillcolor("green") {enter}
t.begin_fill(){enter}
for _ in range(6): {shift-enter}
t.forward(25) {shift-enter}
t.right(60) {enter 2x}
t.end_fill(){enter}
``````

Have fun!