Python - Difference Between Print And Return
Solution 1:
Return stops execution of a whole function and gives the value back to the callee (hence the name return). Because you call it in a for loop, it executes on the first iteration, meaning it runs once then stops execution. Take this as an example:
def test():
for x in range(1, 5):
print(x)
return x
test()
This will give the following output:
1
This is because the for loop starts at 1, prints 1, but then stops all execution at the return statement and returns 1, the current x.
Return is nowhere near the same as print. Print prints to output, return returns a given value to the callee. Here's an example:
def add(a, b):
return a + b
This function returns a value of a+b back to the callee:
c = add(3, 5)
In this case, c, when assigning, called add. The result is then returned to c, the callee, and is stored.
Solution 2:
When you use return, the loop is ended at the first return only. That's why only one name is returned. return is used when you want to return something from one fucntion to other.
That's not case with print. print will keep executing till the loop ends. That's why all track names are printed.
Solution 3:
Return will simply stop executing the function (whether it's a loop, switch, or etc...)!
By using return you can assign a method that returns a value, allowing you to assign that method to a variable.
E.g
def onePlusOne():
return 1+1
You can then assign this method to a variable, like so:
onePlusOneEquals = onePlusOne()
Print will simply print the value to the console. So now you can print the value of onePlusOneEquals, like so:
print onePlusOneEquals
The console will log:
2
Solution 4:
OK... Programming Languages 101 time, kids.
In Python, the print
statement does just that - print the indicated value to the standard output (STDOUT). In this case, you're looping over the entire tracks
array, and printing each value in it.
In most programming languages, the return
keyword will pass the indicated value up to the calling function, where it can be placed in a variable and used for something else. For instance, if you called your function like this:
track = show_recommendations_for_track(someTrackList)
The value of track
would be the first value in someTrackList
. Because return
ends the function immediately, only the first value in the array would be placed in track
, and the rest of the loop would not occur.
Post a Comment for "Python - Difference Between Print And Return"