# Functions Like a traditional mathematical functions, python functions can take an input, process it, and give an output. In python, the input variables are referred to as *arguments*. Functions are blocks of code that is run every time it's called. This allows us to re-use code. Functions are defined by using the def keyword. Reminder: it is important to keep track of indentation as it signify the end of the function when the indentation. ## Defining Functions ### Simple function A simple function with no input variable can be useful if you need to re-use code multiple times without having to re-write it. ```python def function_name(): print("This is from a function") ``` ### Defining a function with one input We can pass variables through to the function to be processed as follows: ```python def function(x): print(x + " is best") ``` Note input variables can be of any data type (integer, float, string, etc.). ### Returning values from a function If we want to calculate a value and pass it back to the script for further use, we can use the `return` keyword. Let's define a linear function that takes two inputs, `x` and `b`, computes the corresponding `y` value, and returns it so it can be used elsewhere in the code. ```python def function(x, b): y = 3*x+b return y ``` For multiple output variables we can add ## Calling functions Now that we've covered defining functions we want to call the function in order to execute the block inside the function. To do this, we simply re-call the function name as follows. ```python function(2,-1) ``` Note that when running this code, nothing happens. This is because we haven't told the computer to print the result. ## Summary ```python def function_name(argument1, argument2, argument3) output1 = argument1 * argument2 - argument3 output2 = argument2 + argument3 return output1, output2 [solution1, solution2] = function_name(1,2,3) ``` - `def` - defines a function. All the code that is indented underneath is considered inside the function block. - `function_name` - this is used to call the function block. - `argument1` (optional) - input variable. This is data that can be pass to the function. It is possible to have multiple variables separated by a comma. As well as can be omitted if the function should just give you an output such as. - `return` (optional) - if you wish to return something to your script, the return keyword is used. The keyword can be followed by an output variable or a constant. For multiple output variables, separate them by a comma.