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

steve10brink at comcast.net steve10brink at comcast.net
Wed Jul 9 17:00:03 CEST 2014


Greetings, 


I've been learning Python concepts for about 6 months now and was doing okay with most of these. However, I ran into a fairly simple program developed by Mark Pilgrim in his "Dive Into Python" text that puzzles me and am hoping some of you can explain how this works. He is creating the Fibonoci sequence by iterating over a function that has a generator in it (i.e. no return statement). The code is as follows: 
---- 

def fibonacci(max): #using a generator 
a, b = 0, 1 
while a < max: 
yield a 
a, b = b, a+b 


for n in fibonacci(1000): 
print n, 
------ 


The program works beautifully buy I can't figure out what we are actually iterating with. When the function is called it 'yields' the value a which is then updated to b, etc. But what is the value of 'n' as it iterates through the function? I can understand iterating through lists, strings, range(), etc. but how this iterates through a function is puzzling me. Obviously the answer, n, is the Fibonocci series but by what mechanism does this work? What is the iterable component of a function? 


BTW, this is one of the many things that fascinates me about Python. It's easy to learn but also has some unique (at least to me) ways of doing things. 


Thanks, 
Steve Tenbrink 
Los Alamos, NM 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140709/c473238a/attachment.html>


More information about the Tutor mailing list