If a function uses the yield keyword, it defines an object known as a generator. A generator is a function that produces a sequence of values for use in iteration.
1.
A generator function is a special kind of function that you can use to define your own iterators. When you define a generator function, you return each iteration's value using the yield keyword. When there are no more iterations, an empty return statement or flowing off the end of the function ends the iterations. Local variables in a generator function are saved from one call to the next, unlike in normal functions:
def four():
x = 0
while x < 4:
print("in generator, x =", x)
yield x
x += 1
>>> for i in four():
print(i)
in generator, x = 0
0
in generator, x = 1
1
in generator, x = 2
2
in generator, x = 3
3
>>> 2 in four()
in generator, x = 0
in generator, x = 1
in generator, x = 2
True
>>> 5 in four()
in generator, x = 0
in generator, x = 1
in generator, x = 2
in generator, x = 3
False
2.
def countdown(n):
print("Counting down from %d" % n)
while n > 0:
yield n
n -= 1
#return
>>>c = countdown(10)
If you call this function, you will find that none of its code starts executing. For example:
>>> c = countdown(10)
>>>
Instead, a generator object is returned.The generator object, in turn, executes the function
whenever next() is called (or
__next__() in Python 3).
Here's an example:
>>> c.next() # Use c.__next__() in Python 3
Counting down from 10
10
>>> c.next()
9
You can also use for statement to loop the generator object.
def countdown(n):
print("Counting down from %d" % n)
while n > 0:
yield n
n -= 1
c = countdown(10)
for i in c:
print i