I am looking at the Python document for turtle graphics, it has an example on drawing the turtle star. the program is as follow:
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
I don't understand why the abs(pos())
works? The abs()
function takes a single argument, but the pos()
function returns a position (x,y) coordinate. I know the program works, just don't understand why. I tried it on the Python interpreter with abs((-0.00,0.00))
, it returns error. Please help!
The abs() function of Python's standard library returns the absolute value of the given number. Absolute value of a number is the value without considering its sign. Hence absolute of 10 is 10, -10 is also 10. If the number is a complex number, abs() returns its magnitude.
The abs() function takes a single argument, but the pos() function returns a position (x,y) coordinate.
The alternative method of abs() function could be by using python exponents. Apply exponent of 2 on a number and then apply 0.5 exponent on the result. This is a quick hack to find the absolute value without using abs() method in python.
pos()
returns a turtle.Vec2D, not a tuple. You can make abs()
work for any type by implementing __abs__()
. In the case of turtle, __abs__()
returns (self[0]**2 + self[1]**2)**0.5
as per the turtle source code here.
The pos()
is not returning a tuple with x and y coordinate, instead it is returning an object of type turtle.Vec2D
, this can be verified using:
>>> type(pos())
>>> turtle.Vec2D
Further if you run dir(pos())
you may get:
['__abs__', '__add__', ... '__class__','count', 'index', 'rotate']
So the turtle.Vec2D
object has its own __abs__
implementation, but a generic tuple
has no such implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With