Generator
In Python, a function that uses yield is called a generator (generator).
Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.
In the process of calling the generator to run, the function pauses and saves all current run information each time the yield is encountered, returning the value of yield. and continue running from the current location the next time the next () method is executed.
The following example uses yield to implement the Fibonacci sequence:
1 #!/usr/bin/python32 3 ImportSYS4 5 defFibonacci (N):#Generator Function-Fibonacci6A, b, counter = 0, 1, 07 whileTrue:8 if(Counter >N):9 returnTen yielda OneA, B = B, A +b ACounter + = 1 -f = Fibonacci (10)#F is an iterator that is returned by the generator - the whileTrue: - Try: - Print(Next (f), end=" ") - exceptstopiteration: +Sys.exit ()
Python3 iterators and generators