oscar.j.benjamin at gmail.com
Mon Feb 25 01:51:28 CET 2013
On 25 February 2013 00:39, Ziliang Chen <zlchen.ken at gmail.com> wrote:
> Hi folks,
> When I am trying to understand "yield" expression in Python2.6, I did the following coding. I have difficulty understanding why "val" will be "None" ? What's happening under the hood? It seems to me very time the counter resumes to execute, it will assign "count" to "val", so "val" should NOT be "None" all the time.
> Thanks !
> code snippet:
> def counter(start_at=0):
> count = start_at
> while True:
> val = (yield count)
> if val is not None:
> count = val
> print 'val is None'
> count += 1
The value of the yield expression is usually None. yield only returns
a value if the caller of a generator function sends one with the send
method (this is not commonly used). The send method supplies a value
to return from the yield expression and then returns the value yielded
by the next yield expression. For example:
>>> g = counter()
>>> next(g) # Need to call next() once to suspend at the first yield call
>>> g.send('value for count') # Now we can send a value for yield to return
'value for count'
More information about the Python-list