How To Use Loops With Python Turtle

How To Use Loops With Python Turtle

Drawing shapes with Turtle in Python can be accomplished using a combination of the forward() and right() functions working together. The turtle direction tutorial has an example of how we can draw a square using these commands in Turtle. The example works, but it is not very elegant. We had to call each forward() and right() function a total of four times each in order to draw the square. This type of code repetition can be reduced by using loops in Python. In this tutorial, we’ll look at how to draw some shapes in Turtle using loops.


Square Code

Recall the original code to draw a square in Turtle that looked something like this. Notice the highlighted code which is simply the same two functions called several times in a row.

from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)

shape('square')
left(90)
forward(150)
left(90)
forward(150)
left(90)
forward(150)
left(90)
forward(150)

done()

The for() loop

The same thing can be accomplished with this simple for() loop like so.

from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)

shape('square')
for i in range(4):
    left(90)
    forward(150)

done()

Both pieces of code produce the same result in Turtle.

python turtle loop to draw square


Experimenting With Loops

Loops are a fun way to simply start experimenting to see what the program will draw. Let’s try several examples with various iterations in the loops, and different values passed into the right() and forward() functions to see what happens.

from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)

shape('square')
for i in range(8):
    left(45)
    forward(75)

done()

python turtle octagon


from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)

shape('square')
for i in range(16):
    right(100)
    forward(200)

done()

random shape from loop turtle


from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)

shape('square')
for i in range(48):
    right(100)
    forward(127)
    left(50)

done()

super cool python turtle loop


from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)

shape('square')
for i in range(48):
    right(100)
    forward(70 + i)
    left(50)

done()

python turtle loop magic


from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)

shape('square')
for i in range(75):
    right(20 + i)
    forward(1 + (i * 5))
    right(40 + i)

done()

python turtle graphics wow

As you can see, when incorporating loops into drawing with Turtle, you can come up with all kinds of interesting visual representations!