Last time we went over variables and talked about how there was an easier way to do things; this is that easier way. As mentioned before, we are going to discuss one of the other important building blocks of programming — functions. Now, the question is, what are functions?
What Are Functions?
Functions are a small set of reusable statements/code that allow you to repeat the same set of instructions in multiple places. Given their name, they are also similar to mathematical functions, where they can take input, and produce an output. Remember those print statements from the last post? Those are examples of functions. They perform some operation for you that’s repeatable; this means they can be reused throughout your program more than a variable. To illustrate let’s make our own functions!
Making Our Own Functions
To create our own function, first, we need to decide what it should do and the proper syntax for creating one in Python. Here’s an example of an “add” function:
Simple syntax right? We define a function add with the def keyword then perform addition in the body. Finally, we return the result. Notice we even have type information, allowing you to better understand what it returns. This isn’t the case with all functions.
Some functions do not return anything; if we wanted to represent a function like that it would look similar to the below:
Notice the main difference is the keyword “return” is missing and “pass” is used instead. We also set the return type to “None“, which is similar to “undefined/null” in other programming languages to signify nothing is returned.
Okay, That’s Cool But Trivial!
You might think this is trivial, but it has some important implications on the way you code in the future because just like in Math, you can compose(add them together) functions. Now, before the Math scares you away, it’s really straight-forward but has a couple more parenthesis. Take a look:
As you can see, we used the add function and this new multiply function together to do what we did before in the last post with “three times five”. Now, this chaining behavior is not limited to just numbers.
We can take this chaining behavior an apply it to a lot of different things in our program. Take this chaining behavior to heart as it allows us to do a lot of cool and interesting things we may have not been able to do before without them. Most importantly, it’s a lot easier than having to write a whole bunch of variables everywhere; we can reuse our functions wherever we want in our code.
Stay tuned for more when we get into classes and objects.
Most importantly, keep working on your games!