Level III

Play with functions

Until now, you have already played with blocks of code. Thus, it’s the right moment to learn what a function is!

A function is a block of code that will only run if you call it. The function will expect from you to give it (or input) some data via a method with the function name. The expected data are known as parameters or arguments, and the function will return data as a result, also called output.The structure of a function is the following:

def function_name(parameter1, parameter2, parameter3): #line 1: function definition 
       #your code: do something
       return result 

function_name(argument1, argument2, argument3) #line 3: function call, also called “method”

Here we are defining a function called “function_name”. In Python, it is mandatory to write the word “def” before the function name in order to define it. The data we are using as input are inside braces. 

Wait a second, I thought parameters and arguments were the same thing?

 Yes, these are both the data you input in the function. However, you can use the term “parameter” as the data given inside the parameters when the function is defined (line 1), whereas an argument is the data that is sent when we call the function (line 3).

Please, note that when you call the function, it is performed outside the block of code, such that there is no need of “indentation” with the keyboard button “tab”.

Let’s look at this example:

 

You can write any type of piece of code that you have learned with us in Code For a Change inside the function block. 

Here are some examples:

To prove that we can use any code we have shown you in the previous sections inside a function, let’s introduce again the example of the “thermometer” (see “Play with conditionals” section).

This is what we had before:

Can you see? It seems the variable “my_temperature” can perfectly be chosen and changed by the user, right? Let’s define the function “thermometer”.

These are what are called “User-defined functions”, because you, as a user, decide what the function does. You can get as creative as you want! 

Functions will be really useful to you. You only define them once but you can use them as many times as you want with different parameters; that is, they are reusable. You will save time and lines of code, and more importantly, will be useful to use them when the variables of the problem you are solving change. Get ready to implement your own functions to solve our !