summaryrefslogtreecommitdiff
path: root/tutorials/1_functions.md
blob: edbd3a201232030691e42e6b6babe90869640760 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 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 <code> def </code> 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.