我是Python的初学者,找到了一个用Turtle绘制三角形的代码,如下代码
def drawPolygon(t, vertices):
t.up()
(x, y) = vertices[-1]
t.goto(x, y)
t.down()
for (x, y) in vertices:
t.goto(x, y)
import turtle
t = turtle.Turtle()
t.hideturtle()
drawPolygon(t, [(20, 20), (-20, 20), (-20, -20)])
turtle.done()
我不明白的第一件事是:
(x, y) = vertices[-1]
。
我不明白的第二件事是:
for (x, y) in vertices:
。
在您的代码中,vertices 是传递到函数中的列表,因此
(x, y) = vertices[-1]
只需访问列表中的最后一个元素(-1 表示从末尾开始),并且 (x,y) 是一个用于存储返回值的元组。 for (x, y) in vertices:
只是迭代列表顶点中所有元素的一种方法。
请参阅以下内容以获取更多信息:
https://docs.python.org/3/tutorial/controlflow.html
https://docs.python.org/3/reference/simple_stmts.html#assignment-statements
(x, y) = vertices[-1]
-1
的订阅表示获取数组的最后一个元素,本例中是(-20, -20)
。
for (x, y) in vertices:
将使Python迭代数组中的每个元素,在每次迭代期间,可以通过调用
(x, y)
来访问迭代的元素。
第一行:
(x, y) = vertices[-1]
基本上是在说
取出列表
中的最后一个元素,即vertices
,并将其元素分配给(-20, -20)
和x
。y
因此
x
将等于 -20,并且 y
也将等于 -20。
第二行:
for (x, y) in vertices:
。该行创建了一个 for loop
。
这个特定的循环遍历列表
vertices
,并获取每个值,并使用 .goto()
函数使海龟转到该值。
希望这有帮助!
`来自海龟导入海龟,屏幕
吉姆=海龟()
定义边(边): 角度 = 360 / 边数 对于 _ 在范围内(no_of_sides): 吉姆.转发(100) 吉姆.右(角度)
对于 range(3, 11) 中的 no_of_sides: 边数(无边数)
屏幕=屏幕() screen.exitonclick() `