Chapter 3: Custom functions

Euclidean distance function

face Josiah Wang

Let us try to write another function together. Please follow along and implement it together!

Let’s say you would like a function that can compute the Euclidean distance between two points in 2D space.

Euclidean distance

In the spirit of test-as-you-code (incremental development), we can simply start by defining what the function looks like.

def euclidean_distance(x1, y1, x2, y2):
    pass

It is also a good idea to get a feel of how the function can be used. So at this point, we can already write some code that calls our function. Since we know the expected answer, we have also written some code to test the output of our function automatically.

def euclidean_distance(x1, y1, x2, y2):
    pass

distance = euclidean_distance(2, 3, -2, 1)
expected_answer = 4.4721
epsilon = 0.000001
if abs(distance - expected_answer) < epsilon:
    print("Test passed")
else:
    print(f"Test failed. {expected_answer} expected, but {distance} returned.")

This approach of writing code to test your function before you even implement your function is called a test-first approach, a key feature in agile development. The idea is that you start by writing your tests so that you know what kind of behaviour you expect from your function/program. Then you implement your function/program, and make sure that it passes all your tests once you are done.

Now run your code. It will fail. As expected, since you have not implemented anything yet!

TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'

Let’s now just make the function return something. Let’s just return 0. for now. Just to show that you are returning a float.

def euclidean_distance(x1, y1, x2, y2):
    return 0.0

# your test code
...

It is also a good idea to include a docstring as your documentation at this point. This will actually help you think carefully about your function, its inputs and its outputs. We will discuss more about docstrings later in this lesson.

def euclidean_distance(x1, y1, x2, y2):
    """ Compute the Euclidean distance between two 2D points.

    Args:
        x1 (float): x-coordinate of the first point
        y1 (float): y-coordinate of the first point
        x2 (float): x-coordinate of the second point
        y2 (float): y-coordinate of the second point

    Returns:
        float: The Euclidean distance
    """

    return 0.0

# your test code
...

Run your program. It will still fail. But at least it is returning a float now. And you already have some documentation written while your mind is still fresh, and do not have to worry about writing it later. So you’ll remember what this function is meant to do when you come back to it later.

Test failed. 4.4721 expected, but 0.0 returned.