[Tutor] Generators
Tiger12506
keridee at jayco.net
Tue Jul 24 03:24:51 CEST 2007
> I am new to Python but not new to programming languages. I have seen this
> "while 1" a lot. In fact in other languages I would expect "while 1" to
> be
> the same as "while TRUE". I have used that in other languages, but in the
> definition below I would expect the "yield b..." to continue on until a
> "break". So the question is, how does this work without going into an
> infinite loop without a break?
>
> Jeff
while 1: and while TRUE: mean the same thing.
The thing is - it is an infinite loop.
>>> a = fibonacci()
>>> a.next()
1
>>>
No matter how many times you call a.next(), it will continue to return
numbers. You are being fooled by the yield statement. Generators are special
objects.
The yield statement is ~~ difficult to translate into computer terms. My
first impulse is to compare it to an interrupt, but you might not know what
that is.
The best way to explain it is to litter that example with print statements.
Here:
def fibonacci():
a = 1
print "a = 1"
b = 1
print "b = 1"
print "Before yield a"
yield a
print "After yield a"
while 1:
print "Before yield b"
yield b
print "After yield b"
a, b = b, a+b
print "After calculation"
>>> a = fibonacci()
>>> a.next()
a = 1
b = 1
Before yield a
1
>>> a.next()
After yield a
Before yield b
1
>>> a.next()
After yield b
After calculation
Before yield b
2
>>> a.next()
After yield b
After calculation
Before yield b
3
>>>
JS
More information about the Tutor
mailing list