Reputation: 41
I am doing an exercise in the textbook Think Python by Allen Downey. I am sure that the code is correct but it keeps showing the same problem:
Traceback (most recent call last):
File "C:/Users/ADMIN/PycharmProjects/ProgrammingFundamental101/EXTRA EFFORTS/Classes_and_Objects.py", line 80, in <module>
print(distance_between_points(blank.x, blank.y))
File "C:/Users/ADMIN/PycharmProjects/ProgrammingFundamental101/EXTRA EFFORTS/Classes_and_Objects.py", line 74, in distance_between_points
dx = p1.x - p2.x
AttributeError: 'float' object has no attribute 'x'
The code is below:
def distance_between_points(p1, p2):
dx = p1.x - p2.x
dy = p1.y - p2.y
dist = math.sqrt(dx**2 + dy**2)
return dist
print(distance_between_points(blank.x, blank.y))
Both points blank.x and blank.y have been defined and assigned with values of 3 and 4.
What is going wrong with the arguments or the parameter?
Upvotes: 2
Views: 71
Reputation: 41
thanks so much for your effort and time.
After reviewing your suggestions and taking another look through the material. I figured it out.
I created two different points to be used as arguments and it worked!
b = Point()
b.x = 0
b.y = 0
g = Point()
g.x = 3
g.y = 4
print('distance', distance_between_points(b, g))
distance 5.0
Again, thanks so much for such prompt responses!
Upvotes: 2
Reputation: 226
I'm assuming that blank
is a Point
object.
The function is expecting p1
and p2
to be Point
objects. This means that what is needed is
distance_between_points(some_point, another_point)
If python sees some_point.x
it is no longer a Point
object, it's the x coordinate of that some_point
object.
In the code p1
is blank.x
, which means when it does p1.x
it is doing blank.x.x
, which is why python raises that error.
Upvotes: 1
Reputation: 18438
Obviously the code cannot be correct. Otherwise it would not throw an error. :) The error message tells you, what is wrong. In this line:
dx = p1.x - p2.x
You are accessing the x
property of p1
and of p2
. At least one of those two (though I am guessing both) is a float
type object, which does not have an attribute named x
.
Unfortunately, you did not post the context, i.e. where blank
comes from. So I can only guess that it is some sort of object representing a point in 2D-space, which has an x
and a y
attribute representing the point's coordinates as floats. I would assume that the distance_between_points
function expects the arguments to be instances of that same point class. And instead (again, I am just guessing here) you are passing the x
-coordinate of a point as the first and the y
-coordinate as the second argument to the function instead of two different point objects.
If you post the entire relevant context (where blank
comes from), we could verify this.
Upvotes: 1