Python继续与while

时间:2013-10-17 09:19:43

标签: python loops

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

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循环永远不会终止!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

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

在偶数测试

之前移动i += 1

i = 0

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

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