Calculating Distance with Python

Play Treasure Island by Clicking Here

I am very keen to help people connections between Maths and Computer Science. Above is a game I wrote using JavaScript. When you click on an “x” you have a 50% chance of being told the distance from the treasure.

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.

Pythagoras' Theorem in Python

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 (x2, y2).

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[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))


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?

So there you have it – how to calculate the distance between two points with Python, and a fun game to play too.

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *