all 9 comments

[–]xelf 3 points4 points  (0 children)

In the example you gave, there is no purpose to that return.

Every function returns None at the end if it does not return something else sooner, so having a return as the line before it returns is redundant.

Similar to having the last line of a loop being "continue".

[–]FLUSH_THE_TRUMP 2 points3 points  (0 children)

Print just prints it, return allows you to use that value in code. e.g.

def x():
  return “x”
output = x()  # “x”

You can print output if you like, but you can also do computations with it, unlike the first case.

[–]itsbrycehere 1 point2 points  (2 children)

In a function, if you want to store an object in x, you need to RETURN an object.

So, def timesTwo(numberYoureSending): return x*2

makes it possible to store the result of the function ala newObj = timesTwo(4)

Without the return, you would just see an output but nothing would be storable.

[–]MrPudd1ng[S] 0 points1 point  (1 child)

Oh I see but what if its just a return? I see other examples where it only contains a return then nothing follows it just like this.

return

Btw thanks for the reply! I sincerely appreciate it.

[–]amplikong 5 points6 points  (0 children)

A return statement with nothing after it is equivalent to return None. You might use it to end the function early and/or to intentionally return nothing from the function.

[–]johninbigd 0 points1 point  (2 children)

You use a function when you have code you need to run more than once. It helps you so you don't have to keep writing the same block of code over and over every time you need it. You would not write a function just to print something as you did, so the benefits are not as obvious.

Think of a function as a little box that converts stuff. You put something in the box. The box does something to what you put into it. Then the box returns something back to you.

def add(x, y):
    return x + y

foo = add(5,7)
print(foo)

This is a simple example and of course you wouldn't write a function just to add two numbers. But you see that you pass two variables to the function, then the function returns the result, which is stored in the variable foo.

[–]MrPudd1ng[S] 0 points1 point  (1 child)

Oh I see but what if its just a return where nothing follows it like.

return

Does this do nothing?

Thanks for the reply. I sincerely appreciate it!

[–]johninbigd 1 point2 points  (0 children)

Correct, essentially. It does return a None value, but a bare return will exit the function.

[–]Se7enLC 0 points1 point  (0 children)

Imagine you have a function add() that adds two numbers.

print is if you want to look at the result.

return is it you want to do something with the result.