[Tutor] I am having difficulty grasping 'generators'

Alan Gauld alan.gauld at btinternet.com
Wed May 28 13:57:41 CEST 2014


On 28/05/14 11:52, Degreat Yartey wrote:
> This means that  '...' should generally contain a manipulator then yield
> generates from where it stopped...*getting it*


It would help if you deleted the irrelevent bits so we can see
which '...' you mean.

I'm guessing it was this comment, right at the end, by Danny:

>     We _can_ write a loop to run over such infinite sequences, but we'll
>     also have to make sure to stop it manually: it won't exhaust
>     otherwise, so doing something like:
>
>     #################
>     for n in onlyEvens():
>          ...
>     #################
>
>     better have something in the "..." that interrupts or returns, or else
>     that loop will never end.


Notice that the ... here is not part of the generator.
So the ... here references to how you process the output of the 
generator - the yielded values. So in this example case you'd
have something like

#################
for n in onlyEvens():
     if n > 1000: break     # prevent infinite loop
     # now process the evens that we are interested in.
#################

The 'break' could also be a 'return' if the loop were
inside a function.

And it doesn't have to be a direct value check as shown the
condition could be based on some external condition or even
user input. The important point is to make sure that you
have some way to exit the loop if the generator is infinite.

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list