vytasd2013 at gmail.com
Tue Feb 26 18:07:14 CET 2013
You are using "yield" incorrectly. "yield" works like return, but it can
return more than once from the same function. Functions that "yield"
produce a so called "generator" object. This generator object gives you
values every time you call it.
The generator works very interesting way. It starts like normal function
and goes until it finds "yield" and returns the value. The state of
generator is saved - it is like it is put to sleep until you call it again.
So the next time you call generator() it runs from the point it returned
last time and will return you another value.
Simple sample of making and using generator (prints forever, so just kill
"""Returns integer each time called"""
count = start_at
count += 1
generator = counter()
if __name__ == '__main__':
On Tue, Feb 26, 2013 at 4:34 PM, Colin J. Williams <cjw at ncf.ca> wrote:
> On 24/02/2013 7:36 PM, Ziliang Chen 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
> Perhaps it's becaoue (teild count) is a statement. Statements do not
> return a value.
> Colin W.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list