Here is python 3.6
The generator can be defined with yield. The generator saves the algorithm. After each iteration, a value after yield is returned until StopIteration is encountered, and the iteration is completed, that is, next points to StopIteration. This generator cannot be iterated again.
When beginners can't understand yield, treat yield as print, but print is returned to people to see
, yield is returned to the machine
But what happens when we write return when we define the generator with yield
# Traverse this generator, encounter return, stop traversing, # Here return is StopIteration def g2(): yield 'a' yield 'b' yield 'c' return yield 'd' for n in g2(): print(n)
# This return after I iterate completely, # So it seems that this return has no effect def fib(n): a, b = 0, 1 while(n>0): yield a a, b = b, a+b n-=1 return a