Python Lab · Experiment 4
Distance between two points
PythonWeek 1JNTUH R22 · CS206ES
Aim
To write a Python program that reads the coordinates (x1, y1) and (x2, y2) of two points and finds the distance between them.
Algorithm
- Read x1 and y1, the coordinates of the first point.
- Read x2 and y2, the coordinates of the second point.
- Find dx = x2 − x1 and dy = y2 − y1.
- Find the distance d = √(dx² + dy²).
- Print d rounded to two decimal places.
Program
import math
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
dx = x2 - x1
dy = y2 - y1
distance = math.sqrt(dx ** 2 + dy ** 2)
print(f"Distance between ({x1}, {y1}) and ({x2}, {y2}) = {distance:.2f}")Output
Points (1, 2) and (4, 6)
Enter x1: 1
Enter y1: 2
Enter x2: 4
Enter y2: 6
Distance between (1.0, 2.0) and (4.0, 6.0) = 5.00Points with negative coordinates
Enter x1: -2
Enter y1: 3
Enter x2: 4
Enter y2: -5
Distance between (-2.0, 3.0) and (4.0, -5.0) = 10.00Points (0, 0) and (1, 1)
Enter x1: 0
Enter y1: 0
Enter x2: 1
Enter y2: 1
Distance between (0.0, 0.0) and (1.0, 1.0) = 1.41Recorded by running this exact program. Typed input appears after each prompt.
How it works
The formula comes from Pythagoras' theorem: dx and dy are the two shorter sides of a right-angled triangle, and the distance is the longest side.
Because the differences are squared, the order of the points does not matter: the distance from A to B is the same as from B to A.
Check: for (1, 2) and (4, 6), dx = 3 and dy = 4, so d = √(9 + 16) = 5. For (−2, 3) and (4, −5), dx = 6 and dy = −8, so d = √(36 + 64) = 10.
Python 3.8 and later also have math.dist((x1, y1), (x2, y2)), which gives the same answer.
Common mistakes
Forgetting
import mathand gettingNameError: name 'math' is not defined.Writing
dx ^ 2for the square. In Python^is XOR; usedx ** 2ordx * dx.Writing
math.sqrt(dx ** 2) + dy ** 2. The bracket must close after the whole sum:math.sqrt(dx ** 2 + dy ** 2).Reading the coordinates with
int(). Coordinates can be fractions such as 2.5, so usefloat().
Viva questions
Try to answer each one aloud before you open it.
What is the formula for the distance between two points?
d = √((x2 − x1)² + (y2 − y1)²). It comes from Pythagoras' theorem.
Which module gives the sqrt function, and how do you use it?
The
mathmodule. Writeimport mathat the top and callmath.sqrt(x).Does it matter which point is taken as the first point?
No. The differences are squared, so a negative difference gives the same square as the positive one.
What is another way to find a square root without the math module?
Raise the number to the power 0.5, for example
16 ** 0.5gives 4.0.