Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does abs() function works for the position coordinate in Python?

Tags:

python

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!

like image 363
Kathy L Avatar asked Jan 23 '18 05:01

Kathy L


People also ask

How abs function works in Python?

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.

What is abs POS ()) in Python?

The abs() function takes a single argument, but the pos() function returns a position (x,y) coordinate.

How do you get absolute value in Python without abs?

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.


2 Answers

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.

like image 64
Evan Rose Avatar answered Nov 15 '22 03:11

Evan Rose


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.

like image 40
ZdaR Avatar answered Nov 15 '22 03:11

ZdaR