繁体   English   中英

在 while 循环中是否需要 continue 语句?

[英]Is the continue statement necessary in a while loop?

我对在while循环中使用continue语句感到困惑。

在这个高度赞成的答案中,在while循环中使用continue来指示执行应该继续(显然)。 它的 定义还提到了它在while循环中的使用:

continue 只能在语法上嵌套在 for 或 while 循环中

但是在这个(也是高度赞成的)关于使用continue的问题中,所有示例都是使用for循环给出的。

考虑到我运行的测试,它也似乎完全没有必要。 这段代码:

while True:
    data = raw_input("Enter string in all caps: ")
    if not data.isupper():
        print("Try again.")
        continue
    else:
        break

和这个一样好用:

while True:
    data = raw_input("Enter string in all caps: ")
    if not data.isupper():
        print("Try again.")
    else:
        break

我错过了什么?

这是一个非常简单的示例,其中continue实际上做了一些可测量的事情:

animals = ['dog', 'cat', 'pig', 'horse', 'cow']
while animals:
    a = animals.pop()
    if a == 'dog':
        continue
    elif a == 'horse':
        break
    print(a)

你会注意到,如果你运行它,你不会看到dog打印出来。 那是因为当 python 看到continue时,它​​会跳过其余的 while 套件并从顶部重新开始。

您也不会看到'horse''cow' ,因为当看到“ 'horse' ”时,我们会遇到完全退出while套件的中断。

说了这么多,我只想说超过 90% 1的循环不需要continue语句。

1这是完全的猜测,我没有任何真实数据来支持这个说法:)

continue只是意味着跳到循环的下一次迭代。 这里的行为是相同的,因为无论如何在continue语句之后都没有发生任何进一步的事情。

您引用的文档只是说您只能在循环结构内部使用continue - 在外部,它没有意义。

仅当您想跳到循环的下一次迭代而不执行循环的其余部分时,才需要continue 如果它是要运行的最后一条语句,则它无效。

break完全退出循环。

一个例子:

items = [1, 2, 3, 4, 5]
print('before loop')
for item in items:
    if item == 5:
        break
    if item < 3:
        continue
    print(item)

print('after loop')

结果:

before loop
3
4
after loop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM