So far we’ve looked at void functions, or function which execute, and exit – without returning something to the calling program/function. We’ve even looked at passing values to a function, but we often want to return a value from a function.
A value-returning function will return a value back to the calling location. Think of the input function. We pass a value to it (the prompt), and get a string value back.
Everything we’ve done with a function so far (arguments, keyword arguments, multiple arguments) work the same way, just this time we’re going to get a value back.
Consider the modification to a previous function in our example below:
number = get_square(5)
print(number)
def get_square(value) :
return value ** 2
Notice, how we are still getting the square of the value passed in. However, we are now returning the value, instead of printing it out here. This actually increases the usefulness of the function, because we can use it to print, get a value to pass to another function, etc. Previously, we were locked into the one and only outcome, which was printing the square.
Importing Libraries
Python allows us to import libraries of external functions to use in our programs. This is important because it greatly expands what Python can do.
So why not have them in there by default? Well, the more libraries that are automatically loaded, the longer it takes to run a program, and the more bugs that might occur in our run time environment. Plus, something you use all the time, might not be used by 80% of other developers. And Python is a general purpose language – so we want flexibility and speed.
This way, we keep the core functionality small, but flexible.
A simple example of this, is loading the Random library. To do so, we use the import command, and then the library name.
import random
number = random.randint(1, 10)
print(number)
Library functions can be called from within other functions. Consider:
import random
for i in range(10) :
num = get_random(i)
print(num)
def get_random(value) :
return random.randint(value, value**2)
While we’ve looked at returning numbers, you can also return strings, Boolean, you know, any data type. It all works the exact same way.
Returning Multiple Values
One thing different between Python and other languages, is that you can return multiple values at one time. Let’s look at a previous example where we got a user’s first and last name, but modifying it so a function is called to get the values, and put them into two new variables.
def get_names() :
firstName = input("Enter your first name")
lastName = input("Enter your last name")
return firstName, lastName
first, last = get_names()
Returning a Value from a Function was originally found on Access 2 Learn