Python Lessons – 3.4 Values returned by the functions

Python Lessons - 3.4 Values returned by the functions

Functions that return values

In the previous section you have seen that it is not possible to change the value of a variable within a function, even if you pass it as an argument. At the time of any assignment a new variable is created that is destroyed at the end of the function.

So how can you use the functions to work on external variables?

The functions are able to return values at the end of their execution, and to do so you use the return clause.

So if you write

a = 3
def raddoppia(x):
    return x * 2

a = raddoppia(a)
print(a)

if you run it, you get:

>>>
6

As you can see at the end you have a value at the output of the doubling function that is reassigned to the variable a.

In fact, keep in mind that the value exiting a function must always be stored in some variable otherwise it will be lost.

Functions as arguments

Another way to use the functions that return values is to use them directly as arguments in turn. In this case it will be sufficient to write the call to the function as an argument of another function

To apply what we have just said, let’s see an example where we use an IF-ELSE construct to return different values depending on the case. The returned value instead of being assigned to a variable, will immediately be used as an argument to the print () function.

def maggiore(x,y):
    if x >= y:
        return x
    else:
        return y

print(maggiore(4,3))

If you run it, you get

>>>
4

A note about the return clause

Attention to use the return clause inside a function, this has a function similar to break for the cycles, i.e. when the function execution is read terminates, regardless if after it there are other command lines inside the function.

Let’s take an example

def foo():
    return "Valore restituito"

print("Dopo il return")
print(foo()) 

If you run it, you get

>>>
Valore restituito

And there is no trace of the string “After the return” as we would have expected.

⇐ Go to Python Lesson 3.3 – Functions arguments

Go to Python Lesson 3.5 – Comments and Docstrings ⇒

Leave a Reply