Writing Functions
Think of functions as a box.
Input -> Do some stuff with the input -> Output
You put some stuff in the box (called parameters), the box does some stuff with the data, and the box spits out some outputs (called values). It also runs the code inside it during the process.
Let's update our definition for what a typical function looks like.
def function_name(parameters):
# some lines of code here
return value
Let's take a look at an example:
def add_two_numbers(a, b):
return a + b
In this example, the values of a
and b
are passed into the box, and the box spits out the value of a + b
.
To use this function, you need to call it by running:
add_two_numbers(1, 2)
tip
Note that the return
value of a function is not directly printed! The previous line will not print anything!
To print the result, you would need to explicitly call the function. For example:
print(add_two_numbers(1, 2))