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.
def square(x):
return x * xUse 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.
def square(x):
return x * x
def distance_squared(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return square(dx) + square(dy)- dx
- 3
The sideways gap is 4 minus 1, which is 3.
square(x) returns x times x. What does square(5) + square(2) work out to?
- A29
- B49
- C14
Show the answer
29. square(5) is 25 and square(2) is 4, and 25 + 4 = 29.
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.
x1 = 1, y1 = 2, x2 = 4, y2 = 6 → 25
−1,000 ≤ x1, y1, x2, y2 ≤ 1,000