Skip to content
Home » Functions in Python – The return Statement

Functions in Python – The return Statement

Spread the love

This is just another article in the Functions in Python series. Today we’ll be talking about the return statement.

If you haven’t read the previous two parts yet, feel free to do so. Here they are:

1) Introduction to Functions

2) Functions with Parameters

Functions that DO Something

In all the examples in the previous parts of the series on functions the functions did something (like printing some text), but they didn’t return anything. Let’s have a look at our inch_to_cm function again.

def inch_to_cm(inches):
    print("{} inches = {} centimeters".format(inches, inches * 2.54))

This function just prints a message. But we can’t use the result in calculations or embed it to a string for example, because the result was not returned.

A very nice feature of functions is that they can return some value. This way we can use functions in expressions.

Functions that RETURN Something

Let’s modify our inch_to_cm function so that it doesn’t print a message, but instead returns a value:

def inch_to_cm(inches):
    return inches * 2.54

Now the function returns a float number, so it may be used wherever a float could be. Some examples:

print("The diagonal is 52 inches, which is equal to {} cm.".format(inch_to_cm(52)))

Here’s the output:

The diagonal is 52 inches, which is equal to 132.08 cm.

Or another example:

size = int(input("What diagonal in inches do you need? "))

if size > 100:
    print("Our maximum size is 100 inches, which is 254 cm.")
else:
    print("OK, looks like it's {} cm.".format(inch_to_cm(size)))

A possible output:

What diagonal in inches do you need? 50
OK, looks like it's 127.0 cm.

Or another possible output:

What diagonal in inches do you need? 125
Our maximum size is 100 inches, which is 254 cm.OK, looks like it's 50.8 cm.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Functions Returning Multiple Values

A function may return exactly one object, but it doesn’t have to be a simple object like a string, int or float. It could also be a list, tuple or dictionary. We can use this feature to make the function indirectly return multiple values. Suppose we need a function that takes a list of numbers as a parameter and returns the minimum, the maximum and the average value of all the numbers. We’ll do it in two ways:

– First, let’s make the function return a 3-tuple:

def stats(numbers):
    minimum = min(numbers)
    maximum = max(numbers)
    average = sum(numbers) / len(numbers)
    return (minimum, average, maximum)

print(stats([1, 3, 7, 5]))

And the output is:

(1, 4.0, 7)

– And now let’s make the function return a dictionary:

def stats(numbers):
    minimum = min(numbers)
    maximum = max(numbers)
    average = sum(numbers) / len(numbers)
    return {"min" : minimum, "average" : average, "max" : maximum}

print(stats([1, 3, 7, 5]))

Here’s the output:

{'min': 1, 'average': 4.0, 'max': 7}

We can check the type of what is returned by using the type function:

print(type(stats([1, 3, 7, 5])))

And the result is:

<class 'dict'>

If we passed just stats to the type function:

print(type(stats))

we would get:

<class 'function'>

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Four Possible Cases with the return Statement

As far as the return statement is concerned, we can have four situations:

1) There is no return statement.

In such a case the function ends after the last statement in the function body is executed. The function returns a special value None.

2) There is one return statement followed by an expression.

In such a case the return statement ends the execution of the function. The function returns the value of the expression following the return keyword.

3) There is one return statement but it’s not followed by an expression.

In such a case the function ends and the special value None is returned.

4) There is more than one return statement.

In such a case the execution of the function ends as soon as the first return statement is executed.

The return statements don’t have to be at the end of a function. They can be anywhere inside the body of the function.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Multiple return Statements

Here’s an example of a function with multiple return statements:

def age_descriptor(age):
    if age < 13:
        return "a child"
    elif 13 <= age < 18:
        return "a teenager"
    else:
        return "an adult"

Now we have three possible execution paths depending on the age passed as an argument. Only one execution path will be followed, so only one return statement will be executed. Let’s try this function out on the following code:

cousins = {"Luke" : 28, "Anne" : 11, "Jenny" : 6, "Mike" : 17}

for cousin in cousins:
    stage_of_life = age_descriptor(cousins[cousin])
    print("My cousin {name}, {age}, is {0}.".format(stage_of_life, name = cousin, age = cousins[cousin]))

In the for loop we’re iterating over the keys of the dictionary. We use the values from the dictionary as the arguments to the age_descriptor function. Here’s the output:

My cousin Luke, 28, is an adult.
My cousin Anne, 11, is a child.
My cousin Jenny, 6, is a child.
My cousin Mike, 17, is a teenager.

Ternary if Statement after return

What the function returns may be conditional. You can use a ternary if statement to decide what should be returned. Have a look at this function with three parameters:

def ordered(number1, number2, number3):
    return True if (number1 <= number2 <= number3) else False

This function returns True if the three numbers passed as arguments are ordered from smallest to largest. Otherwise it returns False. As the function returns a boolean value, we can use it in conditional statements:

if ordered(4, 5, 7):
    print("4, 5 and 7 are ordered.")
else:
    print("4, 5 and 7 are not ordered.")

if ordered(5, 2, 7):
    print("5, 2 and 7 are ordered.")
else:
    print("5, 2 and 7 are not ordered.")

And here’s the output:

4, 5 and 7 are ordered.
5, 2 and 7 are not ordered.

Spread the love

Leave a Reply