5.2 Function Output
Capturing Function Results
So far, our functions took arguments (inputs), but they only produced output on the terminal using print(). Printing alone is limited because the value just appears on the screen. Although it looks like it produces something, Python itself doesn’t know about it anymore once it’s printed.
Functions are more useful if they produce output that can be put in a variable. To capture what a function produces so you can reuse it, you must use a return statement.
Whatever follows the return statement of a function becomes the function’s return value. The function exits at the return statement. To use that return value to a variable, use the function call as if it’s a variable.
To illustrate how this works, create the following python script named example_fun_output.py through the text editor:
2
3
4
5
6
7
def addone(x):
return x+1
a = 10
b = addone(a)
print(a,b)
What happens here?
- The function
addonetakes one argumentx. - It computes
x + 1and returns that value. - You can assign the returned value to a variable (in this case,
b).
What will happen if we run this file in the terminal?