Veja o exemplo abaixo para definir uma sequência infinita:
Python 2
def fibonacci_generator():
f1=0
f2=1
while True:
yield f1
f1, f2 = f2, f1 + f2
#yield does not stopIteration like return
#it passes a value to whoever called next(),
#and saves the "state" of the generator function
if __name__ == '__main__':
f=fibonacci_generator()
for i in range(10):
print f.next()
Python 3:
def fibonacci_generator():
f1=0
f2=1
while True:
yield f1
f1, f2 = f2, f1 + f2
#yield does not stopIteration like return (it creates a generator)
#it passes a value to whoever called next(),
#and saves the "state" of the generator function
if __name__ == '__main__':
f=fibonacci_generator()
for i in range(10):
print (f.__next__())
# Ou
# for i in range(10):
# print (next(f))