# Functions- Return Value

I’m really struggling with the use of the Return option in functions. Why do we have to use return, and when do we know when to use it. I have tried not using return, and it always comes back with 0, that bit I have understood. But I just can’t understand when to use it?

This is an example:

def calculate_exchange_usd(us_dollars, exchange_rate):
return us_dollars * exchange_rate

new_zealand_exchange = calculate_exchange_usd(100, 1.4)

print(“100 dollars in US currency would give you " + str(new_zealand_exchange) + " New Zealand dollars”)

As for multiple returns, that just boggles me. I would really appreciate and explanation!

Functions in programming are named after mathematical functions. A common way to describe a function in math is a black box that takes some sort of input from the user and generates a predictable output. The people that use the box (the function) don’t really need to know how it does what it does most of the time, they just need to get the desired output.

So it can be thought of as just that: an input-output box with a pre-defined role. A very easy example is a function that doubles your input. For example, you put in 3, you get back 6. Mathematically this is f(x) = 2x. Note that the input itself is not modified, x is still 3 if that’s the input. The output f(x) is what is double the input. Just like if you pay money at vending machine and press 4 for a can of soda, your input (money+button press 4) does not become the output (the soda).

In programming (as opposed to math) however, functions have another powerful facet: they can change the state of things. This is probably how a lot of people who don’t come at from math see it first (I know I saw it this way first). You “invoke” this function (like invoking a spell) and something special happens.

And then one last note, names of things. At a very low level (assembly) a function is called by an instruction at a certain address, operations then switch over to the function for it to do what it needs to do. Finally, when it is done, it returns to the address of the caller, so that the program may resume as intended (and when it returns, it may have a basket of goodies that we know as return values).

1 Like