A function is a collection of code expressions to be executed.
Functions are used to organize and reuse code
We’ve actually been calling functions for a while now!
We can PASS values to functions, and then values can be RETURNED to us
We can create our own functions, so that we can perform tasks without having to rewrite code
Rewriting code is the worst
Suppose we were writing a small 2D physics-based game. We might need to know the slope of a surface, to determine if a player can stand on that surface. We’ve written this code before:
#The variables below are all floatsslope = (y2 - y1) / (x2 - x1)
OK, so the code above works… but what if we want to calculate the slope of a different line?
See how we’re duplicating code here? It may not seem like a big deal now, but having to remember and rewrite the slope formula all over the place is annoying! It’s also error-prone… what if we accidentally put a variable in the wrong place in the equation? OK, so… what do we do to solve this problem?
What if we could somehow refer to that chunk of code we’re using for slope, without having to rewrite it everywhere? Maybe it’d look something like the following:
We could use “SlopeOfLine” to refer to our chunk of code from earlier. Whenever we have need of it, we could use that name, and pass things TO it, to WORK on! (remember… instructions and data). Well… sure, it’d be neat if we could do something like this:
#When we use THIS NAME...SlopeOfLine(x1, y1, x2, y2)#We're actually referring to THIS CODE below: (y2 - y1) / (x2 - x1)
But to name a chunk of code and reuse it like that, we’d need to learn about functions! Let’s shelve our example for now, and come back to it in a bit.
Functions!
Functions are present in basically every programming language. They’re a way to wrap any number of code expressions together in a little package, so that they can be used repeatedly in different contexts.
We’ve used a number of different functions already. Remember how we discussed Python’s built-in functions? So far we’ve mostly called the things below “utilities” or some other word… but they’re actually functions!
print("Hello World!")phrase = input()
Functions usually take some input and produce some output (though they aren’t required to do either).
To use a function (which is CALLING or INVOKING a function), we write out the name of the function, and then put parentheses. If the function takes input, the input goes in the parentheses:
print("This string is being passed to a function!")
So this is all well and good… but we haven’t yet talked about how to write a function in code. We’ve seen some functions we’ve used before, and we now know how to call a function if we ever made one… so how do we MAKE them?
Writing our own functions
If we wanted to write a function of our own, how would we do that?
Let’s look at a simple example:
The code above is something we haven’t seen before. It’s called a ==function declaration==.
OK, so what’s actually going on here? There are a number of parts we need to look at:
Function Name: TimesTwo
The name of the function is “TimesTwo”. This is how we’d refer to this chunk of code, if we wanted to use it in some other part of our program. We also use the def keyword before the function name. This means we’re defining a function.
Argument/Parameter: myNumber
This function needs a value to do its job (data for the instructions). That value is an integer, and inside the function we refer to it as myNumber. This function has a single argument, but we could write a function with two, three… or zero arguments! For a function definition, the argument must have a name, just like a newly created variable.
You’ll notice I used two different words above: argument and parameters. There is a difference between what these two things are, but I don’t think this distinction is important for our purposes. For now, just use the word argument, but know that if you see the term parameter, they’re basically interchangeable.
Function Body
The body of the function is code that multiplies our number by 2, and then RETURNS that value. Return is a special keyword that is used to end a function’s execution, and give a value back to the calling code. When we return dubNumber, we’re copying the value from dubNumber and passing it back to the portion of code that called the function originally.
Tying it all together
So how would we write out our slope function?
Write out the function definition for the function Slope
So what’s up with that special keyword called return? It’s a way for our functions to give something back to whoever called them.
Think of it kind of like going to the counter at a bakery. You go to the counter, and give the baker what they need to do their job; in this scenario, say it’s a description of a cake and the money to pay for the cake. The baker then says “sure thing, one moment please!”, heads into the kitchen, and comes back out with the cake you requested. You can think of the baker like a function! They received some stuff from you (arguments, the money and cake description), did some work (the body of the function, the act of making the cake) and now they’re returning the cake to you (the return statement at the end of the function).
The Slope function from earlier returns a float value, which means when we call it, we should probably assign a variable to the value it returns:
slopeB = SlopeOfLine(x3, y3, x4, y4)
Not all functions have to return things though! Maybe a function is only used to call some very specific print statements and won’t give the caller anything back! It just depends on what the function is being used for.
Yo Dawg, we heard you like functions…
Functions can actually call OTHER functions entirely! And of course, we’ve also been doing this all along! Looking back at the example above, main is a function, and EatBoolean is a function… and we’re calling EatBoolean from inside main. But we can go deeper with this:
We can follow the flow of code, through these function calls, to see what is happening.
Our program starts at the bottom, where it creates some variables, gets input, and then calls AreCollinear.
AreCollinear uses the arguments to then call SlopeOfLine.
SlopeOfLine calculates the slope of a line. The slope is returned from this function as a float.
Back in the AreCollinear function, the SlopeOfLine function is called a second time.
SlopeOfLine calculates the slope of another line. The slope is returned from this function as a float.
Back in the AreCollinear function, we compare the slopes, and return a boolean value from AreCollinear, to tell us whether or not the three points are collinear.
Finally, this boolean value is stored in the answer variable..