As well as handing values to your functions, functions can also hand values back to the calling line. This is known as the return value.
What we'll do is to have our function add up, and then return that answer to the line where we called the function into action.
In your addition function from the previous section, delete the print line. Now add this in its place:
Your code will then look like this:
To get something back from a function, you use the keyword return. After a space, you then type the value that you want out of your function. For our code, we'd like the answer to the addition of first_number and second_number.
We now need to change our calling line. At the moment, it's this:
This is set up to just execute a function. It's not set up to get anything back from a function. To do that, you need to put your function name on the right of an equals sign. To the left of your equals sign, you set up a new variable to store the value returned by the function. Amend your calling line to this:
additionTotal = addition(3, 5)
The function goes off and does its thing. When it's got an answer, it comes back with that answer and stores it in the variable we've called additionTotal.
Add a print statement to see what you get back:
print("The addition total was", additionTotal)
And here's what your code should look like:
Try your code out. When you run it, you should see this in the output window:
The addition total was 8
Functions can return any value you like, not just numbers. You can set them up to return strings, lists - whatever it is your program needs. Just remember that to get a value back, you need your function on the right of an equals sign. To the left on of the equals sign, you need a variable to store the value coming back from your function.
Before we get on to something called default function values, a short digression on Booleans in Python.
Python Boolean Values
A Boolean value is one that's either True or False, Yes or No, 1 or 0. In Python, you can set up a Boolean like this:
myTest = False
If you place a zero in myTest above, it will also be evaluated to False:
myTest = 0
Another way to say False in Python is this:
myTest = None
A pair of empty quotes will also get evaluated to False:
myTest = ''
myTest = ""
There are one or two more expressions that will get evaluated to False.
If you want to set a value to True, you can do so explicitly. Like this:
myTest = True
Or store a 1 in the variable:
myTest = 1
You can test for True or False with If Statements:
If myTest == True:
print("It's not true")
Now, back to functions. Let's explore default values in Python functions. We'll do that in the next lesson.