Search code examples
pythonturtle-graphicspython-turtle

Using loops in Python Turtle


Here is my code. I want to edit this and make each side of the star a different color. So five different sides of a star meaning five different colors.

Essentially each side of the star has a different color. I am able to use any five colors. And also preferably I want to use loops. How can I do this?

import turtle

def star(color, sides, length, angle, distance):
    galileo = turtle.Turtle()
    galileo.color(color)  # colorful!
    galileo.width(5)  # visible!
    galileo.speed(0)  # fast!
    galileo.penup()
    galileo.left(angle)  # away from center
    galileo.forward(distance)
    galileo.pendown()  # start drawing
    for side in range(sides):
        galileo.forward(length)
        galileo.left(720 / sides)
    galileo.hideturtle()  # just the star

for angle in [180, 135, 90, 45, 0]:
    star("red", 5, 50, angle, 100)

for angle in [180, 135, 90, 45, 0]:
    star("blue", 5, 30, angle, 60)


Solution

  • You can just set the color in the for loop in the star() function instead of passing it as a parameter, for example

    colors = ['red', 'green', 'yellow', 'blue', 'orange']
    for side, color in zip(range(sides), colors):
        galileo.color(color)  
    

    zip() takes two iterables and 'zips' them together, so zip([1,2,3], ['a', 'b', 'c']) becomes [(1, 'a'), (2, 'b'), (3, 'c')]