I am trying to learn how to use generators, so I wrote this one, but it just prints the same value all the time. Why?
I want it to generate values from 999 down to 100.
>>> def gen_a():
a=999
while a>99:
yield a
a-=1
>>> gen_a().next()
999
>>> gen_a().next()
999
>>> gen_a().next()
999
Because you are generating the generator over and over.
Try:
f = gen_a()
f.next()
f.next()
You're creating a new generator each time. Try this instead:
>>> g = gen_a()
>>> g.next()
999
>>> g.next()
998
>>> g.next()
997
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With