Suppose we want to try out several values for a given expression (eg. 5*x + 11 - x/2).
We could copy the first statement multiple times and replace with each value we want to evaluate. What if we want to change the expression? We should apply the change to all copies respectively.
We could wrap the expression in a function.
You can think of a function as a process which receives some input and produces some output. Inputs to a function are called *arguments* and the output product is what the function *return*s.
In fact you allready used the built-in function print()
.
In Python a function is defined with the def
keyword that marks the start of the function header.
We then define a unique function name in the same way as variables,
enclose the input parameters (parameter1, parameter2, ...)
in parenteheses
and put a colon :
to mark the end of the function header.
All statements that define the function body should be equally indented (4 spaces are commonly used, the editor should handle this automatically)
At the end, the return keyword (optional) gives the function output (if any).
Let's see how we can define a function that multiplies a given variable by 3:
def triple(x): # x is the input number to be tripled
product = 3 * x
return product # this is what the function outputs
Now let's use this function to produce some results
tripled = triple(5)
print(tripled)
15
We can also pass a variable as parameter to a function
test = 5
tripled = triple(test)
print(tripled)
15
Now let's try several values by wrapping an expression into a function
def my_function(x):
return 5*x + 11 - x/2
result = my_function(4)
print(result)
result = my_function(6)
print(result)
result = my_function(8)
print(result)
result = my_function(9)
print(result)
result = my_function(10)
print(result)
29.0 38.0 47.0 51.5 56.0
No problem, we can put as many as we need.
Let's take for instance (x*3 + y/2 - 9):
def my_function2(x, y):
return x*3 + y/2 -9
print(my_function2(4, 8)) # functions can also be nested
print(my_function2(1, 1))
print(my_function2(40, 24))
print(my_function2(-100, 6))
7.0 -5.5 123.0 -306.0
Use the cell bellow to write your own function.
Call this function multiple times with deifferent parameters and print the output.
Once you are ready, click on Kernel
tab > Restart & Run All