Distance between points on a 2D plane is something we calculate using Pythagoras’ Theorem. If you need a reminder, maybe check out mathsisfun or the image below for a condensed version.
We are going to Write a Python program to compute the distance between the points (x1, y1) and (x2, y2). You are going to need to be a little bit flexible with your reasoning about variables here. In the code,
p1 is point 1, which corresponds to
(x1, y1), and similarly,
p2 corresponds to
We can do this with or without a function.
Lets look at the most simple way first:
import math p1 = [4, 0] p2 = [6, 6] distance = math.sqrt(((p1 - p2) ** 2) + ((p1 - p2) ** 2)) print(distance)
Notes: – Don’t just copy-paste. You should study the code, then try and reproduce it yourself. If you get stuck, then copy by typing, not pasting. You will learn much more this way, I promise. – We’ve used lists instead of tuples to keep things simple – if that makes no sense, don’t worry.
Depending on your experience level, you may be able to put the distance-calculating code into a handy re-usable function. Try this as an exercise for yourself if you like. Hint: what would the parameters be?
import math def distance(p1, p2): return math.sqrt(((p1 - p2) ** 2) + ((p1 - p2) ** 2)) p1 = [4, 0] p2 = [6, 6] print(distance(p1, p2))
So there you have it – how to calculate the distance between two points with Python, and a fun game to play too.