Doubt on generators behavior
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Oct 13 05:14:23 EDT 2013
On Sun, 13 Oct 2013 13:49:53 +0530, 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.
Correct. Follow the program logic. The first time you call next,
execution of the generator begins:
- the generator first prints "The number is 78";
- the "if" block is then checked, since 78 is an even number the
line "yield var" is executed and 78 is yielded;
- after "yield", execution halts until you call next again;
- when you call next the second time, execution continues following
the if...else block, which reaches the end of the function and
StopIteration is raised.
> 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.
Again, follow the program logic. The first time you call next, execution
of the generator begins:
- the generator first prints "The number is 77";
- the "if" block is then checked, since 77 is an odd number the
"else" clause is executed, and "The number is off" is printed;
- execution continues following the if...else block, which reaches
the end of the function and StopIteration is raised.
Execution only halts at a yield statement. Try experimenting with this
one:
def example():
var = 3
print "Starting with", var
yield var # pauses after this
print "execution continues..."
var -= 1
print "var now has result", var
yield var # pauses after this
var -= 1
print "var now has result", var
yield 1000 + var # pauses after this
yield "nearly done" # pauses after this
print "Finished now."
--
Steven
More information about the Python-list
mailing list