DSA Factory
Free lessonsProgramming basics · Stage 5 · Functions · Step 1

A function you write yourself

Give a small job its own name, then use it as often as you like. About 9 minutes.

A named recipe

A function is a recipe with a name. You give it ingredients, called parameters, and it hands back a finished dish, called the return value. You have been writing functions all along: every problem in this course asks you to fill one in.

The word return is how the dish comes out. The moment return runs, the function is over and its answer goes back to whoever asked. In Python a function starts with def. In the other languages you write the type of the answer before the name.

Parameters go in, and return sends one answer back.
In code
def square(x):
    return x * x

Use it again and again

Why write your own small functions? Because the same job often comes up twice. To find the distance between two points on a map you square the sideways gap and square the upward gap. Writing the squaring out twice is clumsy and easy to get wrong.

Write a helper called square once. Then call it by name wherever you need it. Your answer's function stays short, and it reads like a sentence.

Write the job once, call it by name every time.
In code
def square(x):
    return x * x

def distance_squared(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    return square(dx) + square(dy)
From (1, 2) to (4, 6)
dx: 3
0
dy: ?
1
square(dx): ?
2
square(dy): ?
3
answer: ?
4
line
dx
3

The sideways gap is 4 minus 1, which is 3.

Move 1 of 5
Quick check

square(x) returns x times x. What does square(5) + square(2) work out to?

  1. A29
  2. B49
  3. C14
Show the answer

29. square(5) is 25 and square(2) is 4, and 25 + 4 = 29.

Your problem

Distance squared

Return the squared distance between two points on a map: the sideways gap squared plus the upward gap squared. Write a small helper function to do the squaring.

Example
x1 = 1, y1 = 2, x2 = 4, y2 = 6 → 25

−1,000 ≤ x1, y1, x2, y2 ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding