473,785 Members | 2,916 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

yield keyword usage

hi
coulde any one show me the usage of "yield" keyword specially in this
example:
"""Fibonacc i 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 (ma**@diveintop ython.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,

Jul 30 '07 #1
3 6937
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:
"""Fibonacc i 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 (ma**@diveintop ython.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®
er**@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
Jul 30 '07 #2
On Jul 30, 4:40 pm, Erik Jones <e...@myemma.co mwrote:
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:
"""Fibonacc i sequences using generators
This program is part of "Dive Into Python", a free Python book for
experienced programmers. Visithttp://diveintopython. org/for the
latest version.
"""
__author__ = "Mark Pilgrim (m...@diveintop ython.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.
Also note that the function could terminate without ever executing
a yield statement (if max<0). In which case nothing would get printed
just like in

for n in []: print n,

You could also force the generator to abort rather than relying
on the while loop not executing by using a return instead of a yield
statement. This can be useful if the while executes even when given
bad arguments.

def fibonacci(max):
if max < 0: # test for invalid argument
print 'max must be >0' # diagnostic message
return # kill generator
a, b = 0, 1
while a < max:
yield a
a, b = b, a+b

for n in fibonacci(1000) :
print n,

print
print

for n in fibonacci(-1000):
print n,
## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
##
## max must be >0

>
Erik Jones

Software Developer | Emma®
e...@myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online athttp://www.myemma.com
Jul 30 '07 #3
Ehsan wrote:
hi
coulde any one show me the usage of "yield" keyword specially in this
example:
"""Fibonacc i 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 (ma**@diveintop ython.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,
A function body with at least one yield expression (formerly a yield
statement) in its body returns a generator when called:
>>def gen(i):
.... for k in range(i):
.... yield k*k
....
>>g = gen(3)
g
<generator object at 0x7ff2822c>
>>>
The same function can be called multiple times to create independent
generators - the particular example I have given created a generator for
a given number of squares.

The generator can be used in an iterative context (such as a for loop),
but in actual fact it observes the Python iterator protocol, so the
generator has a .next() method, which can be used to extract the next
value from it. Calling the .next() method runs the generator until a
yield expression is encountered, and the value of the yield expression
is the return value of the next method:
>>g.next()
0
>>g.next()
1
>>g.next()
4

When the generator function terminates (either with a return statement
or by dropping off the end) it raises a StopIteration exception. This
will terminate an iteration, but in other contexts it can be handled
just like any other exception:
>>g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
So the fibonacci example you quote is a generator function that will
yield a sequence of Fibonacci numbers up to but not including the value
of its argument.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Jul 31 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3685
by: Tobiah | last post by:
def maker(): for i in range(100): yield i foo:4: Warning: 'yield' will become a reserved keyword in the future File "foo", line 4 yield i ^ SyntaxError: invalid syntax
3
2767
by: km | last post by:
Hi all, i didnt understand the purpose of 'yield' keyword and the concept of 'generators' in python. can someone explain me with a small example how generators differ from normal function calls? kindly enlighten regards, KM
12
2255
by: Ioannis Vranos | last post by:
Just some thought on it, wanting to see any explanations. It was advised in this newsgroups that we should avoid the use of keyword register. However it is a language feature, and if it offers no help to an implementation, it is free to ignore it. And this happens widely, all my C++ compilers in my platform ignore this keyword.
54
2717
by: Sahil Malik [MVP] | last post by:
What the heck - I can't find it. A bit shocked to see it missing though. So "Does VB.NET have the yield keyword, or any equivalent of it" ? -- - Sahil Malik Upcoming ADO.NET 2.0 book - http://tinyurl.com/9bync ----------------------------------------------------------------------------
22
2219
by: Mateuszk87 | last post by:
Hi. may someone explain "yield" function, please. how does it actually work and when do you use it? thanks in forward mateusz
2
3775
by: cartoper | last post by:
I am coming to VB.Net from C#. One feature I really like about C# is the yield contextual keyword. Here is what MSDN says about it: -------------- Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration. It takes one of the following forms: yield return expression; yield break; --------------
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10330
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10153
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9952
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.