A point identified by the co-ordinates X1,Y1 is at a distance from the point identified by the co-ordinates X2,Y2. Let’s write a Python program to find the distance between two points.

How to find the distance between two points?

The distance between two points (X1,Y1) and (X2,Y2) can be calculated using the formula given below.

  • Distance between two points= Square Root of ((X2-X1)*(X2-X1) + (Y2-Y1)*(Y2-Y1))

The sqrt function from math module of Python can be used to calculate the distance.

Python code (to calculate the distance)

#Program to find the distance between two points
import math
print("Enter co-ordinates of first point")
x1 = int(input("X co-ordinate "))
y1 = int(input("Y co-ordinate "))
print("Enter co-ordinates of second point")
x2 = int(input("X co-ordinate "))
y2 = int(input("Y co-ordinate "))
d = math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))
print("The distance between the two points is ", d)

Python code (to calculate distance using function)

The code to calculate the distance between two points can be written using a function, which accepts the two co-ordinate values and returns the distance.

import math

#Function to find the distance between two points
def distance(x1, y1, x2, y2):
    d = math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))
    return d

#code to test the above function
print("Enter co-ordinates of first point")
x1 = int(input("X co-ordinate "))
y1 = int(input("Y co-ordinate "))
print("Enter co-ordinates of second point")
x2 = int(input("X co-ordinate "))
y2 = int(input("Y co-ordinate "))
print("The distance between the two points is ", distance(x1,y1,x2,y2))

Similar Programs

Last modified: March 27, 2023

Author