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

Deb Wyatt codemonkey at inbox.com
Wed Jul 9 18:00:02 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,
> ------
> 
> 
> Thanks,
> Steve Tenbrink
> Los Alamos, NM

I am pretty new to Python myself, so I don't know all that much, but you can get a visualization of how the code works at the following website.  It is a highly useful tool.  just copy/paste and step through. 

http://www.pythontutor.com/visualize.html#mode=edit

Deb in WA, USA

____________________________________________________________
FREE ONLINE PHOTOSHARING - Share your photos online with your friends and family!
Visit http://www.inbox.com/photosharing to find out more!




More information about the Tutor mailing list