Now that we've clarified how to use functions, how can we create one of
our own? Let's write our own function to add two numbers together in
order to see how this works.
When defining a function, you have to start with the keyword
def
, and then give it a name. Names for functions should
follow all the same rules as names for variables.
After the function name, we have a pair of parentheses with any
parameters inside them. Here, instead of giving specific values, we use
new variable names. The order we place the variables inside the
parentheses here determines the order that we need to follow when using
the finished function later on.
Just like with if statements, we end this line with a colon and indent
anything that goes in the body of the function underneath.
In our function, we want to add the two numbers together, so we can add
a line like result = a + b
. If we call the function now,
though, and try to print the value of result
, it won't work:
def sum(a, b):
result = a + b
sum(5, 9)
print(result)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# NameError: name 'result' is not defined
In order to access the value of that variable, we first have to
return
it.
return
is another Python keyword with a special meaning.
Its job is to take a value from inside the function and bring it
outside. So in our example, if we return the value of
result
, we can then use that returned value to create and
print the variable total
:
def sum(a, b):
result = a + b
return result
total = sum(5, 9)
print(total)
# 14