Write a program that draws a colorful caterpillar.

Your caterpillar should:

Have 8 body circles
Have circles that alternate between 4 different colors
Hints:

Write one function to draw a body circle and fill in its color using a parameter named color_choice.
A for loop can also shorten your code!

1 answer

You can create a colorful caterpillar using the Python turtle graphics library. Below is a simple program that fulfills your requirements:

Code

import turtle

# Set up the screen
screen = turtle.Screen()
screen.bgcolor("lightblue")

# Create a turtle named "caterpillar"
caterpillar = turtle.Turtle()
caterpillar.speed(2)

# Function to draw a body circle
def draw_circle(color_choice):
    caterpillar.fillcolor(color_choice)
    caterpillar.begin_fill()
    caterpillar.circle(20)  # Circle with radius 20
    caterpillar.end_fill()
    
# List of colors to alternate
colors = ['red', 'yellow', 'green', 'blue']

# Draw the body of the caterpillar
for i in range(8):
    draw_circle(colors[i % len(colors)])  # Alternate colors
    caterpillar.penup()
    caterpillar.forward(50)  # Move forward to draw the next circle
    caterpillar.pendown()

# Hide the turtle and finish
caterpillar.hideturtle()

# Finish drawing
screen.mainloop()

Instructions to Run

  1. Make sure you have Python installed on your computer.
  2. Save the code into a file named caterpillar.py.
  3. Run the file using Python (python caterpillar.py).
  4. A turtle graphics window should open, displaying a colorful caterpillar made up of 8 circles.

Explanation

  • The program initializes a turtle graphics window with a light blue background.
  • A draw_circle function is created to draw a filled circle with the specified color.
  • The main loop uses a list of colors (['red', 'yellow', 'green', 'blue']) and alternates them for each of the 8 body circles.
  • The caterpillar moves forward after drawing each circle to space them out.
  • Finally, the turtle is hidden, and the program keeps the window open until closed.