Screwing Up looping in Generator

Deborah Swanson python at deborahswanson.net
Tue Jan 3 21:05:13 EST 2017


Chris Angelico wrote, on January 03, 2017 3:35 PM
>> On Wed, Jan 4, 2017 at 10:05 AM, Deborah Swanson 
> <python at deborahswanson.net> wrote:
> > Ok, I learned how to use generators in Python 2.7.8, which may be 
> > different from Python 3 for generators. But I learned from MIT's 
> > online introduction to python course, and they certainly 
> seem to know 
> > python well. So what is the correct way to call the 
> generator's next 
> > yield in Python 3? We only learned to use the next function. If you 
> > don't use the next function, what do you use?
>> The built-in next function, not the next method.
>> # don't do this
> gen.next()
>> # do this
> next(gen)
>> ChrisA

You speak the truth! I never doubted, but since I still have 2.7.8 on my
system I decided to try it out.
For a simple little Fibbonacci number generator:
def genFib (): 
 fibn_1 = 1 #fib(n-1) 
 fibn_2 = 0 #fib(n-2) 
 while True: 
 # fib(n) = fib(n-1) + fib(n-2) 
 next = fibn_1 + fibn_2 
 yield next 
 fibn_2 = fibn_1 
 fibn_1 = next
and at the console:
>>> fib = genFib()
>>> fib.next()

2.7.8 works, and cranks out as many Fibbonacci numbers as you could
want.
But in 3.4.3 you get:
Traceback (most recent call last):
 File "<pyshell#13>", line 1, in <module>
 fib.next()
AttributeError: 'generator' object has no attribute 'next'
Then, going the other way, next(fib) works in both versions. 


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /