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
Point A: (1, 2) Point B: (7, 10) Distance between A and B: 10.0
How it works
dxanddyare the horizontal and vertical gaps between the points, here 6 and 8.- The two gaps and the straight line between the points form a right-angled triangle, with the line as the longest side.
- 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. - 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()
Distance: 10.0 3D distance: 7.0
math.dist() takes two points as tuples and works for any number of dimensions.
Manhattan distance
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises