def gen_yy(): yield 1 yield 2 def gen_yr(): yield 1 return 2 print('Correctly prints 1 and 2') for i in gen_yy(): print(i) print('-'*15) print() print('Only prints 1, skips printing 2') for i in gen_yr(): print(i) print('-'*15) print() print('Actual use case for returning from a generator') def external_function(r): return r < 0.10 from random import random def work_until_something_goes_wrong(): while True: r = random() if external_function(r): return -1 else: yield 0 print('This will never print the -1 returned as StopIteration(-1)') for result in work_until_something_goes_wrong(): print(result) print('-'*15) print() # it's too late to retrieve the -1 from the generator because it's reference is lost # the -1 was raised to the for-loop as StopIteration(-1) however the loop body doesn't execute the final iteration so -1 isn't printed