Reputation: 309
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:
.
Upvotes: 2
Views: 3097
Reputation: 2270
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 tox
andy
.
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!
Upvotes: 1
Reputation: 27567
(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)
.
Upvotes: 1
Reputation: 512
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
Upvotes: 2