Breaking out of for loop for current irteration

98 Views Asked by At

I have a loop with a conditional check at some point, is there a way that I can exit the current iteration if the condition is true but still continue looping.

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

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

This code gives me:

Stage 1
Stage 2
Stage 1
Stage 2
Stage 1

But I would like this:

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

The highlighted line shows that it skipped the second print statement for element 'Three'.

Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

You meant to use continue instead of 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
2
On

C language offers the continue keyword. Here is an example that prints all odd < 100

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