return

Effects and results: the return instruction

All the previously presented functions have some kind of effect - they produce some text and send it to the console.

Of course, functions - like their mathematical siblings - may have results.

To get functions to return a value (but not only for this purpose) you use the return instruction.

This word gives you a full picture of its capabilities. Note: it's a Python keyword. The return instruction has two different variants - let's consider them separately.

return without an expression

The first consists of the keyword itself, without anything following it.

When used inside a function, it causes the immediate termination of the function's execution, and an instant return (hence the name) to the point of invocation.

Note: if a function is not intended to produce a result, using the return instruction is not obligatory - it will be executed implicitly at the end of the function.

Anyway, you can use it to terminate a function's activities on demand, before the control reaches the function's last line.

def happy_new_year(wishes = True):
    print("Three...")
    print("Two...")
    print("One...")
    if not wishes:
        return
    
    print("Happy New Year!")

return with an expression

The second return variant is extended with an expression:

def function():
    return expression

There are two consequences of using it:

it causes the immediate termination of the function's execution (nothing new compared to the first variant) moreover, the function will evaluate the expression's value and will return (hence the name once again) it as the function's result. Yes, we already know - this example isn't really sophisticated:

def boring_function():
    return 123

x = boring_function()

print("The boring_function has returned its result. It's:", x)

Don't forget:

  • you are always allowed to ignore the function's result, and be satisfied with the function's effect (if the function has any)

  • if a function is intended to return a useful result, it must contain the second variant of the return instruction.

Wait a minute - does this mean that there are useless results, too? Yes - in some sense.

Note: None is a keyword.

There are only two kinds of circumstances when None can be safely used:

when you assign it to a variable (or return it as a function's result) when you compare it with a variable to diagnose its internal state. Just like here:

value = None
if value is None:
    print("Sorry, you don't carry any value")

Don't forget this: if a function doesn't return a certain value using a return expression clause, it is assumed that it implicitly returns None.

Last updated