Skip to content
Laviyx Learn

Try

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

  1. Read x1 and y1, the coordinates of the first point.
  2. Read x2 and y2, the coordinates of the second point.
  3. Find dx = x2 − x1 and dy = y2 − y1.
  4. Find the distance d = √(dx² + dy²).
  5. Print d rounded to two decimal places.

Program

Python
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)

Output 1
Enter x1: 1
Enter y1: 2
Enter x2: 4
Enter y2: 6
Distance between (1.0, 2.0) and (4.0, 6.0) = 5.00

Points with negative coordinates

Output 2
Enter x1: -2
Enter y1: 3
Enter x2: 4
Enter y2: -5
Distance between (-2.0, 3.0) and (4.0, -5.0) = 10.00

Points (0, 0) and (1, 1)

Output 3
Enter x1: 0
Enter y1: 0
Enter x2: 1
Enter y2: 1
Distance between (0.0, 0.0) and (1.0, 1.0) = 1.41

Recorded 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 math and getting NameError: name 'math' is not defined.

  • Writing dx ^ 2 for the square. In Python ^ is XOR; use dx ** 2 or dx * 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 use float().

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 math module. Write import math at the top and call math.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.5 gives 4.0.

Learn the concepts

All Python Programming Lab experiments →