I don't understand the use for return

Hello everyone.
I am new to coding and I’ve been going through the Python basic course.
I came across the return lesson and to be honest I just don’t understand use for it.

For example, I have the following code:

def estimated_time_rounded(estimated_time):

  rounded_time = round(estimated_time)

  return rounded_time

estimate = estimated_time_rounded(0.5)

I don’t understand why I would return the variable rounded_time.
I’ve already saved the estimated_time into rounded_time so why can’t I just call the function and save it to estimate without having a return in the function?

I just don’t get the use for a return and I was hoping to get some help with this.

Hey there and welcome to the forums :wave:

The variable name rounded_time can only be used with in the function estimated_time_rounded. When the function ends that variable is deleted. The return allows you to save it outside the function.

It might help to note that you could skip rounded_time altogether and just return round(estimated_time):

def estimated_time_rounded(estimated_time):
  return round(estimated_time)


estimate = estimated_time_rounded(0.5)

And though farther down the road, a single line function can be shortened even further, with the lambda keyword, to something like:

estimated_time_rounded = lambda estimated_time: round(estimated_time)
1 Like

Thank you for the welcome!
So if I get this right, the return keyword allows me to save a variable that exists only inside a specific function and use it outside of it?

How, for example, can I use the rounded_time variable outside of the function? I just tried to print it and got an error.

When you assign a function call to a variable name, like you did here:

estimate = estimated_time_rounded(0.5)

That function’s return value will be saved to the variable.
So estimate will be assigned the same value as estimated_time_rounded's return.

When you call a function in an assignment, you can think of it as giving you something. The return is what it will give you.

1 Like

Ohh so when I return something in a function and then call the function to a variable, the return of that function is what is actually saved to the variable?

1 Like

You’ve got it!

And we can test this in a couple ways.

  1. We define a function and print a call to it:
def add(x, y):
  return x + y

print(add(1, 2)) # prints 3
  1. Or we can save it to a variable and print that:
def add(x, y):
  return x + y

result = add(1, 2)
print(result) # prints 3
1 Like

I understand now, thank you very much for your help!

1 Like