Allow me to give an example on why to use this else
-clause. But:
- my point is now better explained in Leo’s answer
- I use a
for
- instead of awhile
-loop, butelse
works similar (executes unless break was encountered) - there are better ways to do this (e.g. wrapping it into a function or raising an exception)
Breaking out of multiple levels of looping
Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.
for k in [2, 3, 5, 7, 11, 13, 17, 25]: for m in range(2, 10): if k == m: continue print 'trying %s %% %s' % (k, m) if k % m == 0: print 'found a divisor: %d %% %d; breaking out of loop' % (k, m) break else: continue print 'breaking another level of loop' breakelse: print 'no divisor could be found!'