-6
for ele in eles:
   for i in xrange(10):
       try:
            #do something
           break
        except:
            continue
   else:
       if some condition:
           continue
       #do something

consider above code, i know the break will break the inner for loop, the first continue will continue inner for loop, what about the second continue? which for loop will it continue?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
stamaimer
  • 6,227
  • 5
  • 34
  • 55
  • 7
    Why not try an example and see? Think about this, though - is the inner `for` loop still running when the `else` block is reached? – jonrsharpe Apr 20 '15 at 10:53
  • Insert a `print()` and see which one `continue`s. – user Apr 20 '15 at 10:54
  • 2
    @musefan: the `else` is executed if the `for` loop completed without being interrupted. E.g. if no `break` statement was executed. Wonderfully useful when [calculating prime numbers](http://stackoverflow.com/a/568684) for example. – Martijn Pieters Apr 20 '15 at 10:57
  • @MartijnPieters: Ahhh, that is quite interesting... though perhaps not the best choice of keyword using `else`. Also, that prime number example function, would you even need the `else`? Surely it would work just returning true, as it would only be hit if it didn't return false already – musefan Apr 20 '15 at 10:59
  • 1
    @musefan: the poor choice of the `else` keyword has been cited a few days ago on the python-dev mailing list. :) – Andrea Corbellini Apr 20 '15 at 11:01
  • @musefan: yes, the feature is wonderful, the exact word used not so much. – Martijn Pieters Apr 20 '15 at 11:02
  • @AndreaCorbellini link? – jonrsharpe Apr 20 '15 at 11:03
  • @jonrsharpe: [here you are](https://mail.python.org/pipermail/python-ideas/2015-April/032995.html): *in the second case, the for-loop, "else" is not the best choice of keyword* (it was actually posted on python-ideas, not python-dev). – Andrea Corbellini Apr 20 '15 at 14:14
  • @AndreaCorbellini much obliged, thank you! – jonrsharpe Apr 20 '15 at 14:15

1 Answers1

0

The latest continue takes effect on the outer for loop, as demonstrated by the following example:

>>> for x in [1, 2, 3]:
...     for y in [4, 5, 6]:
...         print('x =', x, 'y =', y)
...     else:
...         continue
...     print('here')
... 
x = 1 y = 4
x = 1 y = 5
x = 1 y = 6
x = 2 y = 4
x = 2 y = 5
x = 2 y = 6
x = 3 y = 4
x = 3 y = 5
x = 3 y = 6

Note that "here" gets never printed.

Also, note that the inner for loop cannot be continued in any way: the else block is executed when the iterator is exhausted (in my example: when all the ys in [4, 5, 6] have been printed) and when no break statements have been executed. Because the iterator has been exhausted, there are no ways to make it produce more values.

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69