-5

Python 中的 continue 似乎存在一些严重问题:例如:

for i  in range(1,10):
    if i % 2 == 0:
         continue
     print i

按预期工作,但是

i = 0

while(i < 10):
    if i %2 == 0:   
        continue
    i += 1
    print i

while 循环永远不会终止!

4

2 回答 2

5

i在第二个片段中永远不会增加。删除继续。

i = 0
while(i < 10):
    if i %2 == 0:   # i == 0; continue without increment the value of i <-- stuck here!
        continue
    i += 1
    print i
于 2013-10-17T09:21:07.320 回答
3

您的while循环与您的for循环不同;for循环从1开始并始终递增i

在偶数测试i += 1 之前移动:

i = 0

while(i < 10):
    i += 1
    if i % 2 == 0:   
        continue
    print i

因为0 % 2 == 0is True,所以你总是继续,跳过i += 1andprint i语句。

于 2013-10-17T09:26:38.783 回答