When using an else statement, what is the difference between print() and a return for the string? The platform gives an example using print(“some string”) then expects return “some string”. Is there a difference?
return literally does what it says, handing back/returning data to the caller (the function call), while
So if it is a string that is returned upon the function call then printing the same string is doing exactly the same thing as a return? I see the use of literally but I do not understand a difference between the two. I know the example in use was a print() function below else:
I am not sure why the lesson would say one thing then expect a different answer. I did find a decent explanation on stackoverflow.
"Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it."
Hopefully that helps a few others that draw a blank from running through this lesson section.
Lets say we have the following function:
def example(): x = 3
x now is a local variable, there is no way for us to access this variable outside the function
unless we use
def example(): x = 3 return x y = example() print(y)
now this example is a bit lame, but I hope you can imaging if the function did something more interesting,
return can become very useful
return also allow us to pass data between functions, meaning you can make re-usable blocks of code/functions.
Yeah, I think I have a better grasp of it when we start talking about the reusability. Thank you for this.
Ideally, you want each function to have one responsibility. The function name can then describe what the function does. This makes your code easier to test, read and maintain.
I think that explains it, I thought I understood the difference until I read the garbage analogy.
I am not sure either. The rest seems to make sense.