LET’S MAKE COOKIES! An intro to Functions

--Originally published at Coding The Future

Photo by Jade Wulfraat

When I think of functions in any programming languages, I think of them as the reusable tools you use when baking cookies, for example. Here's why...

Every time you make cookies, you don't buy a new bowl, a new mixer, a new oven, and a new tray, or do you? If you do, you're just... something else. However, must of us reuse the same materials. There's obviously the ingredients that are single-use only, but most of the stuff can be reused and that is a good thing, because that way there's no need to buy a new tray every time we want to bake cookies.

Translating this into programming, if we are going to be using the same code several times, there's no point in writing it several times. It only makes sense to write it once, and use it (or call it as many times as we need to.

So basically, a function is "a block of organized, reusable code that is used to perform a single, related action" 1 that improves the efficiency and speed of your code. Remember that less lines of code means also better readability.

Defining a Function

When defining a function, start by typing the keyword def (I'm guessing it's short for define), followed by a unique name for the function, and then include brackets where any input parameters will also be declared (think of input parameters as the single-use ingredients that can change depending on what you want to achieve). Close the line with a colon.

In the following lines, which are always indented, is where the magic happens. You can include a explanation what the function does in the first line in quotation marks, although this is optional. This will not affect your function, and is often referred Continue reading "LET’S MAKE COOKIES! An intro to Functions"