Path: csiph.com!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder2.enfer-du-nord.net!cs.uu.nl!news0.firedrake.org!news.xcski.com!ncf.ca!not-for-mail From: "Colin J. Williams" Newsgroups: comp.lang.python Subject: Re: yield expression Date: Tue, 26 Feb 2013 13:44:06 -0500 Organization: National Capital Freenet, Ottawa, Ontario, Canada Lines: 88 Sender: fn681@206-47-113-19.dsl.ncf.ca Message-ID: <512D0276.5040909@ncf.ca> References: NNTP-Posting-Host: 206-47-113-19.dsl.ncf.ca Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: theodyn.ncf.ca 1361904248 13277 206.47.113.19 (26 Feb 2013 18:44:08 GMT) X-Complaints-To: complaints@ncf.ca NNTP-Posting-Date: 26 Feb 2013 18:44:08 GMT Cc: python-list@python.org To: "Vytas D." User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20130215 Thunderbird/17.0.3 In-Reply-To: Xref: csiph.com comp.lang.python:39986 On 26/02/2013 12:07 PM, Vytas D. wrote: > Hi, > > 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 with CTRL+C). > > def counter(start_at=0): > """Returns integer each time called""" > > count = start_at > while True: > yield count > count += 1 > > def main(): > generator = counter() > > while True: > print(next(generator)) > > > if __name__ == '__main__': > main() > > > Hope helps. > > Vytas D. > > > > On Tue, Feb 26, 2013 at 4:34 PM, Colin J. Williams > 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 > else: > print 'val is None' > count += 1 > > > Perhaps it's becaoue (teild count) is a statement. Statements do > not return a value. > > Colin W. > > > > -- > http://mail.python.org/__mailman/listinfo/python-list > > > Yes, it's very helpful. Thanks also to the other two responders. This brings us back to the OP question. Why not " val = (yield count)"? Colin W.