2016-06-14 28 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聲明正在工作,只是不符合您的期望。