This article mainly introduces the usage of the python generator. The example analyzes the usage skills of the python generator. if you need it, refer to the example in this article to illustrate the usage of the python generator. Share it with you for your reference. The details are as follows:
Yield allows a function to generate a result sequence, not just a value.
For example:
Def countdown (n): print "counting down" while n> 0: yield n # generate an n value n-= 1 >>> c = countdown (5) >>> c. next () counting down 5 >>> c. next () 4> c. next () 3
Next () calls the generator function until the next yield statement is run. at this time, next () passes the return value to yield. the Function suspends execution. When next () is called again, the function continues to execute statements after yield. This process continues until the function returns.
Generally, next () is not called manually as above, but a for loop is used, for example:
>>> for i in countdown(5): ... print i ... counting down 5 4 3 2 1
The return values of next () and send () are all parameters after yield. The difference between send () and next () is that send () is an expression that sends a parameter to (yield n, as the return value to m, and next () is to send a None to (yield n) expression. The difference here is that one is to call next (), send () when the return value is (yield n), the two are different. the output result can be differentiated.
def h(n): while n>0: m = (yield n) print "m is "+str(m) n-=1 print "n is "+str(n) >>> p= h(5) >>> p.next() 5 >>> p.next() m is None n is 4 4 >>> p.send("test") m is test n is 3 3
I hope this article will help you with Python programming.