Getting Started – Functions
Getting Started - Functions
Introduction
If you have programmed in other languages you know the power of functions. If not, this is a good place to practice with them. When you start working with Python, at some point you will have to do task repetatively. This is when you should start thinking about putting your code into functions. We suggest you start practising with functions as much as you can. They can be fun to work with and speed up your development.
Building a function
Let’s build a simple function first and then we will explain it.
def add(variable01, variable02):
sum = variable01 + variable02
print (sum)
return;
Our function is made of ‘blocks’:
- The function begins with the keyword ‘def’ followed by the function
name of the function, in this case ‘add’ and parentheses ‘( )’ - The input parameters, in this case, ‘variable01’ and ‘variable02’ should be
placed within these parentheses separated by a comma. - This first line of this code block ends with a colon ‘:’.
- In the second line (and subsequent lines), you can instruct the function of what action to take.
- In the function ‘add’ the first action is to create a variable called ‘sum’.
- This variable includes the summation of ‘variable01’ and ‘variable02’. You will recognize these parameters as you put them in the brackets on line 1.
- The third action is to display the variable ‘sum’, which we created earlier.
- The last statement is “return” ends the function. It can be given the option to give a value.
Click on the ‘Try yourself’ tab to see how this function, and another function, works.
Try Yourself
Now that we built our function, let’s see if it works. In the console below, we have prepared the add function.
- First press the ‘run’ button.
- Second, in the shell on the right-hand side type in the following code:
add(5,6)
. You may choose other digits if you want to. - While you are there try out the ‘mult’-function
def add(variable01, variable02):
sum = variable01 + variable02
print (sum)
return;
# let's try another function. This one multiplies numbers.
def mult(variable03, variable04):
mult = variable03 * variable04
return mult;
# after pressing the 'run' button, type in the shell mult(8,6). or any two digits.