How To Alternate Colors In Python Turtle

In this blog post, we will explore how to alternate colors while drawing shapes using Python’s Turtle graphics library. The Turtle graphics library is a popular tool for teaching programming concepts, as it provides an easy-to-understand visual representation of the code being executed. Alternating colors can not only make your turtle drawings more visually appealing, but also help reinforce the concepts of loops and conditionals in programming.

Getting Started with Python Turtle

Before we can start alternating colors, we need to import the Turtle library and create a turtle object to work with. Here’s a simple example:

import turtle

t = turtle.Turtle()

Now that we have our turtle object, we can start drawing shapes and changing colors.

Changing the Color of the Turtle Pen

To change the color of the turtle pen, we can use the color() method. For example, to set the color to red, we can do the following:


Alternating Colors in a Loop

Now, let’s say we want to draw a square with alternating colors. We can do this by using a loop and changing the color within the loop. The following code demonstrates this:

colors = ["red", "blue"]

for i in range(4):
    t.color(colors[i % 2])

In this example, we first define a list of colors we want to alternate between. Then, we use a for loop to iterate over a range of 4 (the number of sides in a square). Inside the loop, we set the color of the turtle pen using the modulus operator (%) to alternate between the colors in the list. Finally, we move the turtle forward by 100 units and turn it right by 90 degrees to draw the square.

Using a Function to Alternate Colors

Another way to alternate colors is to define a function that changes the color based on a given index. Here’s an example:

def alternate_color(index):
    colors = ["green", "yellow"]
    t.color(colors[index % len(colors)])

for i in range(4):

In this example, we define a function called alternate_color() that takes an index as an argument. Inside the function, we define a list of colors and set the turtle pen color based on the modulus of the index and the length of the color list. Then, we use a for loop as before to draw the square and call the alternate_color() function inside the loop to change the color.


In this blog post, we explored how to alternate colors in Python’s Turtle graphics library. By using loops, conditionals, and functions, you can create visually appealing turtle drawings and reinforce important programming concepts. Happy coding!