在 Python Turtle 中使用循环

Using loops in Python Turtle

这是我的代码。我想编辑它,让星星的每一面都有不同的颜色。所以一颗星星的五个不同面意味着五种不同的颜色。

基本上星星的每一面都有不同的颜色。我可以使用任何五种颜色。而且最好我想使用循环。我该怎么做?

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)

您可以在 star() 函数的 for 循环中设置颜色而不是将其作为参数传递,例如

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

zip() 将两个可迭代对象 'zips' 放在一起,所以 zip([1,2,3], ['a', 'b', 'c']) 变成 [(1, 'a'), (2, 'b'), (3, 'c')]