You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Turtle绘制交替颜色正方形行失败,仅显示单一颜色

问题分析与解决

你的代码核心问题是颜色判断的变量用错了:

  • 你写的num_squares % 2 == 1是在判断正方形的总数量是奇数还是偶数,一旦调用函数时的总数量确定(比如这里传的是6),这个条件的结果就固定不变,导致所有正方形都用同一种颜色。
  • 要实现交替颜色,应该判断当前正在绘制的是第几个正方形,也就是用循环变量square(从0开始的索引)来做模运算。

修正后的代码:

def square_line(num_squares, color1, color2):
  for square in range(num_squares):
    # 用当前正方形的索引做模运算,实现颜色交替
    if square % 2 == 0:
      t.fillcolor(color1)
    else:
      t.fillcolor(color2)
    t.begin_fill()
    for sides in range(4):
      t.forward(25)
      t.right(90)
    t.end_fill()
    t.penup()
    t.forward(25)
    t.pendown()

square_line(6, 'blue', 'green')

运行这段代码后,就会画出蓝、绿、蓝、绿……交替排列的正方形,完全符合你用模运算符实现颜色交替的需求。

内容的提问来源于stack exchange,提问作者Blythe Kinderknecht

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 11:00:46