For example, the Fibonacci sequence: 1,1,2,3,5,8,13,21,34 .... It can't be written with a list generation, but we can print it out using a function: Def fib (number): N, a, b = 0, 0, 1 while n < Numbe R:print (b) A, B = B, A + b n = n + 1 return ' ok! ' Print (FIB (5)) Results: 1 1 2 3 5 ok! We can see that starting with the first element, the subsequent arbitrary elements are deduced. Very much like generator. To turn the FIB function into a generator, just change print (b) to yield B: def fib (number): N, a, b = 0, 0, 1 While n < Number:yield b A, B = B, A + b n = n + 1 Return ' ok! ' Print (FIB (5)) #<generator object fib at 0x105606ca8> Note: It is difficult to understand that generator and function execution flow is not the same. The function is executed sequentially, the return statement is encountered, or the last line function statement is returned. Note: The function creates one generator at a time,So we'll assign the created generator to a variable. If we use the function itself as a generator, we do not have to generate a new generator object at a time, so we typically assign the created generator to a variable. The Generetor function, which executes at each call to next (), encounters a yield statement return, and executes again from the yield statement that was last returned.
The python generator implements the Fibonacci sequence