data_garden data_garden - 1 month ago 5x
Python Question

python - difference between print and return

If I print the result of the

for loop
in this

def show_recommendations_for_track(tracks = [], *args):

results = sp.recommendations(seed_tracks = tracks, limit=100)
tracks = results['tracks']
for track in tracks:
print track['name']

It prints one hundred track names.

If I swap
return track['name']

it prints only one track name.



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):
        return x


This will give the following output:


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.