Custom Functions#
We have used built-in functions in past lessons. Functions have a name and parameters. Some of them return a result, others don’t. We typically call them using result = function_name(parameters)
.
See also
Let’s take a look at some functions, for example, print(text)
and pow(x, y)
.
The print function takes a parameter (or multiple parameters) and returns nothing:
result = print('Hello world')
Hello world
result
The pow function has two parameters and returns a result:
result = pow(2, 3)
result
8
Custom functions#
You can DEFine your own functions using the def
statement. After the def
statement, you should specify your functions’ name and its parameters in parentheses. Afterward follows a colon :
and all following lines of code, which are indented, are part of this function. A final return
statement sends the result back to from where the function was called.
# Definition of the custom function
def sum_numbers(a, b):
# Assignment of a variable within the function
result = a + b
# Return of the variable as the functions' result
return result
You can then call your function as often as you like:
sum_numbers(3, 4)
7
sum_numbers(5, 6)
11
Sometimes, you want to save the result of your function in a variable.
c = sum_numbers(4, 5)
print(c)
9
Simplify code using reusable functions#
Assume you have a complicated algorithm which can tell you if a number is odd or even. Let’s put this algorithm in a function and call it later on. For our algorithm, we will use the modulo operator %.
Also see the available operators.
def print_odd_or_even(number):
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
print_odd_or_even(3)
3 is odd
print_odd_or_even(10)
10 is even
Thus, instead of writing the same if-else
block again and again, we can just call our custom print_odd_or_even
function.
Documenting functions#
You can document what a function does in its so-called doc string. The doc string follows right after the functions’ header (the first line) and looks like this:
def square(number):
"""
Squares a number by multiplying it with itself and returns its result.
"""
return number * number
You can then later read the documentation of the function like this:
print(square.__doc__)
Squares a number by multiplying it with itself and returns its result.
Also try to use the ?
operator if you want to have the docstring shown as Introspection side-by-side in your notebook:
square?
By the way, you can do this with any function:
import math
print(math.sqrt.__doc__)
Return the square root of x.
print(math.exp.__doc__)
Return e raised to the power of x.