Search code examples
pythonpython-3.xturtle-graphicspython-turtle

Draw Triangle by turtle


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:.


Solution

  • In your code, vertices is a list passed into the function, so (x, y) = vertices[-1]just access the last element in the list (-1 means first from the end), and (x,y) is a tuple to store the values returned. for (x, y) in vertices: is just a way of iterating through all elements in the list vertices.

    Refer these for more info:

    https://docs.python.org/3/tutorial/controlflow.html

    https://docs.python.org/3/reference/simple_stmts.html#assignment-statements