The definition of the generator function is no different from that of a common function. You only need to use yield in the function to generate data items. The generator function can be traversed by the for loop, and the yield generation can be obtained through the next () method.
Data items.
Def func (n): for I in range (n): yield ifor I in func (3): Print IR = func (3) print R. next () print R. next () print R. next () print R. next ()
0
1
2
0
1
2
Traceback (most recent call last ):
File "generator. py", line 10, in <module>
Print R. Next ()
Stopiteration
Yield Reserved Words and return statement return values and execution principles are different. The value generated by yield is not aborted.ProgramAfter the return value is returned, the program continues to run later. After the return value is returned, the program stops execution.
The generator function returns only one data item at a time, consuming less memory. Each time data is generated, the current status is recorded to facilitate the next generation of data.
Use the generator function when the program requires high performance or only one value at a time for processing. Use a sequence to obtain the values of a group of elements at a time.