def fun():
print('this is a function!')
'''
#secction 1
#no while loop, run follow code and exit!
n = 0
yield n
n = n+1
print('over!')
'''
#section 2
n = 0
while True:
yield n
n = n+1
if n == 5:
print('over! and exit!')
return
f = fun() # not execute the func() fucntion
print('call the fun')
for i in f:
print('i = %s'%i)
有以下几点需要明确:
1. 生成器和函数是不相同的,对于函数的话,f = fun(),就会立即执行fun()中的代码段,但是从上图的结果来看,生成器却没有执行,说明f只是一个fun()生成器的一个副本,并没有进行实际的赋值运算
2. 在用next()进行迭代的时候,在生成器fun()中如果执行完毕就会退出
在section 1代码段中,如果没有while循环,就直接执行第二次的时候,就直接退出了
在section 2代码段中,有while循环,就会不断的在while循环中进行迭代,循环执行,直至满足退出条件!