打破当前irteration的for循环

时间:2016-12-23 15:06:44

标签: python loops break

我有一个带有条件检查的循环,如果条件为真但仍然继续循环,有没有办法可以退出当前迭代。

dummy = ['One','Two','Three','Four','Five']

for i in dummy:
    print('Stage 1')
    if i == 'Three':
        break
    print('Stage 2')

这段代码告诉我:

Stage 1
Stage 2
Stage 1
Stage 2
Stage 1

但我想这样:

Stage 1
Stage 2
Stage 1
Stage 2
--------
Stage 1
--------
Stage 1
Stage 2
Stage 1
Stage 2

突出显示的行显示它跳过元素“Three”的第二个print语句。

由于

2 个答案:

答案 0 :(得分:6)

您打算使用continue代替break

>>> dummy = ['One','Two','Three','Four','Five']
>>> 
>>> for i in dummy:
...     print('Stage 1')
...     if i == 'Three':
...         continue
...     print('Stage 2')
... 
Stage 1
Stage 2
Stage 1
Stage 2
Stage 1
Stage 1
Stage 2
Stage 1
Stage 2

答案 1 :(得分:-2)

C语言提供了continue关键字。这是一个打印所有奇数< 100

for(i=0;i<100;i++)
{
    if((i%2) == 0)
    {
         continue;
    }
    printf("%i\n",i);
}