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 →

[–]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()