yield keyword usage

Erik Jones erik at myemma.com
Mon Jul 30 17:40:25 EDT 2007


On Jul 30, 2007, at 4:13 PM, Ehsan wrote:

> hi
> coulde any one show me the usage of  "yield" keyword specially in this
> example:
>
>
> """Fibonacci sequences using generators
>
> This program is part of "Dive Into Python", a free Python book for
> experienced programmers.  Visit http://diveintopython.org/ for the
> latest version.
> """
>
> __author__ = "Mark Pilgrim (mark at diveintopython.org)"
> __version__ = "$Revision: 1.2 $"
> __date__ = "$Date: 2004/05/05 21:57:19 $"
> __copyright__ = "Copyright (c) 2004 Mark Pilgrim"
> __license__ = "Python"
>
> def fibonacci(max):
>     a, b = 0, 1
>     while a < max:
>         yield a
>         a, b = b, a+b
>
> for n in fibonacci(1000):
>     print n,

As in how it works?  Sure, when you use the yield statement in a  
function or method you turn it into a generator method that can then  
be used for iteration.  What happens is that when fibonacci(1000) is  
called in the for loop statement it executes up to the yield  
statement where it "yields" the then current value of a to the  
calling context at which point n in the for loop is bound to that  
value and the for loop executes one iteration.  Upon the beginning of  
the for loop's next iteration the fibonacci function continues  
execution from the yield statment until it either reaches another  
yield statement or ends.  In this case, since the yield occured in a  
loop, it will be the same yield statement at which point it will  
"yield" the new value of a.  It should be obvious now that this whole  
process will repeat until the condition a < max is not longer true in  
the fibonacci function at which point the function will return  
without yielding a value and the main loop (for n in ...) will  
terminate.



Erik Jones

Software Developer | Emma®
erik at myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com





More information about the Python-list mailing list