2016-06-14 54 views
1

工作为什么if不得在下列发电机为什么这个发电机不能在python

def mygen(m): 
    n = 0 
    if n < m: 
     n = n + 1 
     yield n 

counter = mygen(5) 

next(counter) 
1 
next(counter) 
StopIteration 

while做工作?

def mygen(m): 
    n = 0 
    while n < m: 
     n = n + 1 
     yield n 
+0

你是在比较一下吗? For循环与while循环相当。 –

回答

0

while环比较nm反复(直到条件为假),而if声明他们一次比较,然后结束。 if声明正在工作,只是不符合您的期望。

相关问题