Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #56767 > unrolled thread

Re: Doubt on generators behavior

Started byTerry Reedy <tjreedy@udel.edu>
First post2013-10-13 05:43 -0400
Last post2013-10-13 05:43 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Doubt on generators behavior Terry Reedy <tjreedy@udel.edu> - 2013-10-13 05:43 -0400

#56767 — Re: Doubt on generators behavior

FromTerry Reedy <tjreedy@udel.edu>
Date2013-10-13 05:43 -0400
SubjectRe: Doubt on generators behavior
Message-ID<mailman.1050.1381657446.18130.python-list@python.org>
On 10/13/2013 4:19 AM, Krishnan Shankar wrote:
> Hi Friends,
>
> I am new to Generators and was learning the same by experimenting. I
> wrote a small code which is as below.
>
>  >>> def test_gen(var):
> ...     print "The number is", var
> ...     if var % 2 == 0:
> ...         yield var
> ...     else:
> ...         print "Number is odd"
> ...
>  >>>
>
> But when i was executing i saw a behavior i could not understand. When i
> gave an even number,
> 1. The generator object was created
> 2. When i gave next the argument was yielded.
> 3. In the subsequent next the Stop Iteration was raised.
>
>  >>> res = test_gen(78)
>  >>> res.next()
> The number is 78
> 78
>  >>> res.next()
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> StopIteration
>
> But When i ran with an odd number the result of "Number is odd" is
> printed. But it seems the generator runs again by itself to Stop Iteration.

When number is odd, there is nothing to yield, so it raises 
StopIteration on the first next call.

>  >>> res2 = test_gen(77)
>  >>> res2.next()
> The number is 77
> Number is odd
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> StopIteration
>  >>>
>
> How did this happen automatically? I am not able to get the execution of
> a generator. Can someone please help me in understanding?
> Regards,
> Krishnan
>
>


-- 
Terry Jan Reedy

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web