[Tutor] How does this work (iterating over a function)?

Raúl Cumplido raulcumplido at gmail.com
Wed Jul 9 17:24:46 CEST 2014


Hi,

A little bit more on this :)

Python iterator protocol will call the next() method on the iterator on
each iteration and receive the values from your iterator until a
StopIteration Exception is raised. This is how the for clause knows to
iterate. In your example below you can see this with the next example:

>>> gen = fibonacci(3)
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

Thanks,
Raúl


On Wed, Jul 9, 2014 at 4:18 PM, Raúl Cumplido <raulcumplido at gmail.com>
wrote:

> Hi,
>
> Let's see what happens iteration by iteration. First iteration:
>
> def fibonacci(max):  #using a generator
>>
>     a, b = 0, 1
>>
>  # The value of a is 0 and b is 1, easy :)
>
>>     while a < max:
>>
>         yield a
>>
> # yield a (0) (yield is a keyword that is used like return but returns a
> generator). This value will be sent to the for iteration on the first
> iteration.
>
> On the second iteration:
>
>>         a, b = b, a+b
>>
> # a is 1 now and b is 1 (1+0)
> And then yield a which now is 1
>
> On the third iteration:
>
>>         a, b = b, a+b
>>
> # a is 1 now and b is 2 (1+1)
> And then yield a which now is 1
>
> On the forth iteration:
>
>>         a, b = b, a+b
>>
> # a is 2 now and b is 3 (2+1)
> And then yield a which now is 2
>
>
>> for n in fibonacci(1000):
>>     print n,
>> ------
>>
>
> n is the value for each iteration that the yield statement is returning.
> You can read the response on this thread if you want to understand more
> about yield, generators and iterators.
>
> Thanks,
> Raúl
>



-- 
Raúl Cumplido
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140709/ccbbee12/attachment.html>


More information about the Tutor mailing list