Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NameError: name 'distancepoint' is not defined

import math
class point:
    def __init__(self,p1,p2):
        self.p1 = p1
        self.p2 = p2
    def distancepoint(self):
        x1,y1 = self.p1
        x2,y2 = self.p2
        distance = math.sqrt((x1-x2)**2 + (y1-y2)**2)
        return distance
p1 = point(2,4)
p2 = point(1,6)

distance = distancepoint(p1,p2)
print (f'Distance between 2 points: {distance}')

I am a Python beginner. I dont know how to fix this problem.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You have two options here:

  • The way your code is written, distancepoint should be a regular function (outside of a class), that takes two point objects as an input and returns a distance:
import math


class Point: # python devs usually use CamelCase for class names
    def __init__(self, x, y): # x and y, because we have two coordinates, not two points
        self.x = x 
        self.y = y


def distancepoint(p1, p2):
    x1, y1 = p1.x, p1.y
    x2, y2 = p2.x, p2.y

    distance = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
    return distance



p1 = Point(2, 4)
p2 = Point(1, 6)

distance = distancepoint(p1, p2)
print(f"Distance between 2 points: {distance}")
  • Another way to go about it, which you seemed to be aiming at, is to define distancepoint as a method of the Point class. That means you can measure the distance
    from a given Point object to another Point.
class Point: # python devs usually use CamelCase for class names
    def __init__(self, x, y): # x and y, because we have two coordinates, not two points
        self.x = x 
        self.y = y


    def distance(self, other_p):
        x1, y1 = self.x, self.y
        x2, y2 = other_p.x, other_p.y

        distance = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
        return distance

p1 = Point(2, 4)
p2 = Point(1, 6)

distance = p1.distance(p2)
print(f"Distance between 2 points: {distance}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading