【问题标题】:Is the continue statement necessary in a Python while loop?Python while 循环中是否需要 continue 语句?
【发布时间】:2016-07-21 20:24:34
【问题描述】:

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

在这个highly upvoted answer 中,continue 在while 循环中使用以指示执行应该继续(显然)。 definition 还提到了它在 while 循环中的使用:

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

但是在this (also highly upvoted) question中关于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 保留在其中,则可以删除“else”子句)。
  • 两个例子都有相同的行为:continue 在编程上是无用的。在您的示例中,审阅者更容易理解您的算法很有用。 IDE 也可以像 pass 语句一样自动取消缩进下一行。
  • continue 表示:终止循环的本次迭代(即跳过循环体的其余部分)并继续 i> 与下一次迭代。
  • question you linked 的答案已经解释了continue 的意义。他们的示例使用for 而不是while 一点也不重要。 continue 对两种循环都是一样的。

标签: python


【解决方案1】:

这是一个非常简单的例子,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' 也可以通过这种方式避免 animal = ['dog', 'cat', 'pig', 'horse', 'cow'] while animals: a = animals.pop( ) if a == 'horse': break if a != 'dog': print(a)
【解决方案2】:

continue 只是意味着跳到循环的下一个迭代。此处的行为是相同的,因为无论如何在 continue 语句之后不会发生任何进一步的事情。

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

【讨论】:

  • 啊,所以continue 打破了循环的内部,而break 打破了循环的外部。我没听错吗?
  • 是的,这是一种看待它的方式。我经常使用continue 来表达'丢弃这个循环体的其余部分,我们不再对它感兴趣了。但不要退出循环,只需在迭代中丢弃这一步。'
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 2013-08-26
    • 2016-10-07
    • 2010-11-02
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    相关资源
    最近更新 更多