Skip to Main Content
Blog

Calculate Distance between Two Points in Python

Calculate Distance between Two Points in Python

Enter point 1:
x: 2
y: 2
Enter point 2:
x: 6
y: 5
Distance = 5.0
def main():
    """
    Finds the distance between two points in the Cartesian plane.
    """

    print("Enter point 1: ")
    x1 = int(input("x: "))
    y1 = int(input("y: "))
    print("Enter point 2: ")
    x2 = int(input("x: "))
    y2 = int(input("y: "))

    dx = x1 - x2
    dy = y1 - y2
    d = (dx * dx + dy * dy) ** 0.5
    print(d)


if __name__ == "__main__":
    main()

Represent Cartesian point using record

import math


class Point:
	def __init__(self, x, y):
		self.x = x
		self.y = y

	def distance(self, other):
		dx = self.x - other.x
		dy = self.y - other.y
		return math.hypot(dx, dy)  # √(dx² + dy²)


def main():
	print("Enter point 1: ")
	p1 = Point(float(input("x: ")), float(input("y: ")))

	print("Enter point 2: ")
	p2 = Point(float(input("x: ")), float(input("y: ")))

	dist = p1.distance(p2)
	print("Distance:", dist)


if __name__ == "__main__":
	main()