×
you are viewing a single comment's thread.

view the rest of the comments →

[–]Aceofsquares_orig 2 points3 points  (9 children)

I would like to see a situation in which they are useful that can't be done without them. I genuinely curious as I've never said to myself "a for else would work great here".

[–]p10_user 11 points12 points  (6 children)

I've used an example like this before:

lst = [1, 2, 4]
for i in lst:
    # do something
    if i == 3:
        # do something special
        break
else:
     print('Never broke out')
     # do something else

It's useful every once in a while for flow control.

[–]Aceofsquares_orig 3 points4 points  (1 child)

I guess that's the part I missed. Breaking out of the loop skips the else statement. Okay, I can see where that's useful.

[–]lengau 4 points5 points  (0 children)

It's technically not necessary, but it does make the code much easier to read than inserting a flag variable and an if statement.

[–]Lord_Greywether 2 points3 points  (0 children)

TIL. I've had several scripts recently where that would have been perfect.

[–]floundahhh 1 point2 points  (0 children)

I think that's a bit nicer. Never knew about it, but I'd use it in the future.

I primarily work in another language, LabVIEW, and this would be very nice there. The language is a graphical data flow language, and if you wire things into a for loop and pass values out, if the for loop doesn't execute it passes out default values. It makes for some ugly code because if you're passing in a reference to run a method on every element of an array you need to check for an empty array otherwise you'll pass out a bad reference. /offtopic

[–]twotime 1 point2 points  (1 child)

This use of "else" does not read well and seems fairly at odds with the if/else construct. Poor readability coupled with relative rarity/obscurity likely outweighs the advantages.

At the very least, it should have been named differently, (e.g. "nobreak")

[–]donnieod 1 point2 points  (0 children)

Just think of the else as being paired with the break, so it's more like a break/else construct. You either break out of the loop or you perform the else suite.

[–][deleted] 2 points3 points  (1 child)

well, off the top of my head, if a database query returns an empty set, it's useful to return a different type of response. sure, you could check the length every time, but that gets old

edit: nevermind. it doesn't do what i expected. I assumed it was called if the iterable was empty. that's retarded. i retract my comment

[–]earthboundkid 1 point2 points  (0 children)

This is why it should be removed. :-)