import random
def yield_test(n):
for i in range(n):
yield call(i)
print("i=",i)
#做一些其它的事情
print("do something.")
print("end.")
def call(i):
return i*2
def yield_randint(count):
i = 0
while i < count:
i += 1
print('i =', i)
yield random.randint(1, 10)
if __name__ == '__main__':
#example 1
yt = yield_test(5)
for i in yield_test(5):
print(i,",")
#example 2
# rand = yield_randint(10) #create a generator
# for num in rand:
# print(num)
example 1执行结果:
0 ,
i= 0
2 ,
i= 1
4 ,
i= 2
6 ,
i= 3
8 ,
i= 4
do something.
end.
example 2执行结果:
i = 1
7
i = 2
9
i = 3
5
i = 4
2
i = 5
8
i = 6
1
i = 7
5
i = 8
6
i = 9
5
i = 10
2