我同意@TigerhawkT3(+1)你教授对pick_color()的实现是垃圾。但我不认为random.choice(),或者你教授滥用random.shuffle()的方式是最好的选择。两者的问题是,在连续调用时可以获得相同的颜色,这是在正方形内绘制正方形时不需要的:>>> import random
>>> COLORS = ['red', 'blue', 'green', 'yellow', 'black', 'pink', 'gold', 'violet', 'orange', 'magenta', 'cyan']
>>> for _ in range(10):
... print(random.choice(COLORS))
...
green
pink
red
black
violet
orange
orange
violet
yellow
yellow
>>>
我仍然会使用random.shuffle(),尽管不是像你的教授那样,通过跟踪返回的颜色来确保前一次洗牌的最后一种颜色不是新洗牌的第一种颜色:import turtle
import random
COLORS = ["blue", "black", "brown", "red", "yellow", "green", "orange", "beige", "turquoise", "pink"]
def pick_color(colors=[], previous=[None]): # intentionally dangerous default values
if not colors:
colors.extend(COLORS)
random.shuffle(colors)
if colors[-1] == previous[0]:
colors.insert(0, colors.pop())
previous[0] = colors.pop()
return previous[0]
squares = input("How many squares should I draw (whole numbers): ")
squares_int = int(squares)
length = 400
x = -200
y = 200
turtle.pensize(5)
for i in range(squares_int):
random_color = pick_color()
turtle.fillcolor(random_color)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.begin_fill()
for _ in range(4):
turtle.forward(length)
turtle.right(90)
turtle.end_fill()
length -= 30
x, y = x + 15, y - 15
turtle.done()
我相信这比你用相同颜色的相邻方块显示的效果要好: