How to Return Information from Functions in Python
Functions can display data directly in Python or they can return the data to the caller so that the caller can do something more with it. In some cases, a function displays data directly as well as returns data to the caller, but it’s more common for a function to either display the data directly or to return it to the caller.
Just how functions work depends on the kind of task the function is supposed to perform. For example, a function that performs a math-related task is more likely to return the data to the caller than certain other functions.
To return data to a caller, a function needs to include the keyword return, followed by the data to return. You have no limit on what you can return to a caller. Here are some types of data that you commonly see returned by a function to a caller:
Values: Any value is acceptable. You can return numbers, such as 1 or 2.5; strings, such as “Hello There!”; or Boolean values, such as True or False.
Variables: The content of any variable works just as well as a direct value. The caller receives whatever data is stored in the variable.
Expressions: Many developers use expressions as a shortcut. For example, you can simply return A + B rather than perform the calculation, place the result in a variable, and then return the variable to the caller. Using the expression is faster and accomplishes the same task.
Results from other functions: You can actually return data from another function as part of the return of your function.
It’s time to see how return values work. Open a Python Shell window and type the following code:
def DoAdd(Value1, Value2): return Value1 + Value2
This function accepts two values as input and then returns the sum of those two values. Yes, you could probably perform this task without using a function, but this is how many functions start. To test this function, type print(“The sum of 3 + 4 is ”, DoAdd(3, 4)) and press Enter.