[Tutor] How does this work (iterating over a function)?
Raúl Cumplido
raulcumplido at gmail.com
Wed Jul 9 17:18:32 CEST 2014
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140709/2661e5a8/attachment-0001.html>
More information about the Tutor
mailing list