Draw Triangle by turtle

Viewed 486

I am a beginner to python and found a code to draw triangle by Turtle as below code

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()

1st thing I don't understand is this: (x, y) = vertices[-1].

2nd thing I don't understand is this: for (x, y) in vertices:.

3 Answers

The first line: (x, y) = vertices[-1] is basically saying

Take the last element in list vertices, which is (-20, -20), and assigned its elements to x and y.

So x would be equal to -20, and y would be equal to -20 as well.

The second line: for (x, y) in vertices:. That line creates a for loop.

This specific loop goes through the list vertices, and takes each value, and makes the turtle go to that value with the .goto() function.

Hope this helps!

(x, y) = vertices[-1]

The subscription of -1 means to get the last element of the array, and in this case, it's (-20, -20).


for (x, y) in vertices:

Will make python iterate through each element in the array, during each iteration, the element of the iteration is accessible by calling (x, y).

Related