Editor

Python Program to Find the Distance Between Two Points

Beginner · Numbers

The distance between two points (x1, y1) and (x2, y2) on a graph comes from Pythagoras: it is the square root of (x2 - x1)^2 + (y2 - y1)^2. This program applies that distance formula to two points.

Program

distance_between_points.py
import math
x1, y1 = 1, 2 # point A; or: x1 = float(input("Enter x1: ")) and so on
x2, y2 = 7, 10 # point B
dx = x2 - x1 # how far apart the points are sideways
dy = y2 - y1 # how far apart they are up and down
distance = math.sqrt(dx ** 2 + dy ** 2)
print(f"Point A: ({x1}, {y1})")
print(f"Point B: ({x2}, {y2})")
print(f"Distance between A and B: {distance}")
Output
Point A: (1, 2)
Point B: (7, 10)
Distance between A and B: 10.0

How it works

  1. dx and dy are the horizontal and vertical gaps between the points, here 6 and 8.
  2. The two gaps and the straight line between the points form a right-angled triangle, with the line as the longest side.
  3. Pythagoras says that side is the square root of dx ** 2 + dy ** 2, so the distance is the square root of 36 + 64 = 100, which is 10.
  4. Squaring makes the order of the points irrelevant, so swapping A and B gives the same distance.

Other ways to write it

Using math.dist()

Using math.dist()
import math
a = (1, 2)
b = (7, 10)
print("Distance:", math.dist(a, b))
# It works in 3D too
print("3D distance:", math.dist((0, 0, 0), (2, 3, 6)))
Output
Distance: 10.0
3D distance: 7.0

math.dist() takes two points as tuples and works for any number of dimensions.

Manhattan distance

Manhattan distance
x1, y1 = 1, 2
x2, y2 = 7, 10
straight = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
manhattan = abs(x2 - x1) + abs(y2 - y1)
print("Straight-line distance:", straight)
print("Manhattan distance:", manhattan)
Output
Straight-line distance: 10.0
Manhattan distance: 14

Manhattan distance counts steps along the grid, like walking around city blocks, so it is the sum of the two gaps rather than the straight line.

Try it yourself

Find the perimeter of the triangle with corners (0, 0), (4, 0) and (0, 3) by adding up its three sides.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises