2

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

Ann Zen
  • 17,892
  • 6
  • 20
  • 39
Pipo
  • 199
  • 3
  • 20
  • Looks like you took step 2, without taking step 1. I would suggest learn basic python control structures and data structures to understand the programs. If you insist on breaking a leg and learning lessons while learning how to ride bike, there are few helpful souls to support also :-) – aartist Jun 23 '20 at 18:41
  • Thanks @aartist for your comment, actually I am learning now the basics of Python from book and found it hard to understand the previous lines (same book and working with the book sequence), I didn't expect it use a list to assign variables, but I'll be sure to review the basics again to be sure to understand te code easily in the future :) – Pipo Jun 23 '20 at 18:52
  • 1
    https://treyhunner.com/2018/03/tuple-unpacking-improves-python-code-readability/ – Dima Tisnek Jun 25 '20 at 00:53

3 Answers3

2

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

Zircoz
  • 172
  • 12
1

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!

Dima Tisnek
  • 9,367
  • 4
  • 48
  • 106
10 Rep
  • 2,325
  • 7
  • 15
  • 28
1

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

Ann Zen
  • 17,892
  • 6
  • 20
  • 39