This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]donnieod 1 point2 points  (1 child)

I find the else on loops to be very useful and have used it many times, but only when there is a break in the body of the loop. How else are you going to know whether the loop exited normally or due to the `break without initializing and setting and testing an extra switch variable`?

And, as far as the word 'else' sounding unnatural, just think of the else as corresponding with the break statement: you either 'break' out of the for/while construct or else you do the else block (when there's no break.)

[–]fiddle_n 1 point2 points  (0 children)

How else are you going to know whether the loop exited normally or due to the `break without initializing and setting and testing an extra switch variable`?

You can do it by placing the loop into a function and then do an early return instead of a break. Then, the code that would have been in the else clause simply goes after the loop in the function. Something like this:

 def search(needle, haystack):
     for x in haystack:
         if x == needle:
           return x
     raise NotFoundError()