maths computer science pythagoras treasure island

Calculating distance with Python

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:

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.

Leave a Repl​​​​​y

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Get the code for the classic Retro Alien Blitz Game using Python Turtle Graphics when you join our mailing list