python - difference between print and return -
this question has answer here:
- why use return statement in python? 12 answers
if print result of for loop
in function
:
def show_recommendations_for_track(tracks = [], *args): results = sp.recommendations(seed_tracks = tracks, limit=100) tracks = results['tracks'] track in tracks: print track['name']
it prints 1 hundred track names.
if swap print
return track['name']
,
it prints 1 track name.
why?
return stops execution of whole function , gives value callee (hence name return). because call in loop, executes on first iteration, meaning runs once stops execution. take example:
def test(): x in range(1, 5): print(x) return x test()
this give following output:
1
this because loop starts @ 1, prints 1, stops execution @ return statement , returns 1, current x.
return near same print. print prints output, return returns given value callee. here's example:
def add(a, b): return + b
this function returns value of a+b callee:
c = add(3, 5)
in case, c, when assigning, called add. result returned c, callee, , stored.
Comments
Post a Comment