Wednesday, September 30, 2015

Yield Expression and Generator Function in Python

Yield expressions are only used within a generator function. Here is an example:

>>def pp():
     x = yield      #1
     yield x*x       #2
     yield x*x*x     #3
     yield x*x*x*x   #4 
     yield x*x*x*x*x   #5
     yield x*x*x*x*x*x   #6

>>g = pp()
>>next(g)     #starts the generator and executes line #1
>>g.send(5)  #sends value 5 to x at line #2 and gets the result
25
>>next(g)     #gets the result of next line #3
125
>>next(g)     #gets the result of next line #4
625
>>g.send(2)  #gets the result of next line #5 
3125       #cannot send a new value in the middle of execution
>>next(g)     #gets the result of next line #6
15625
>>next(g)    #Throws StopIteration exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

No comments:

Post a Comment