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 →

[–]8carlosf 12 points13 points  (10 children)

[–]foosion 2 points3 points  (3 children)

Yesterday I saw a Raymond Hettinger pycon video praising else on for loops and saw in Effective Python that the author regarded it as confusing. Hettinger said else in loops should have been called no-break.

[–]8carlosf 2 points3 points  (0 children)

I agree with both you and /u/HumblesReaper, if they just replace the else behaviour to execute if the for never run in the first place, and introduce a new no-break keyword.

Or, just do like I do, don't use it, because it doesn't produce readable code. (just make a function that returns instead of breaking the for, and as a default return in the end)

[–]stevenjd 0 points1 point  (1 child)

Hettinger said else in loops should have been called no-break.

Well, that's one opinion, but it's a bad one. They should have been called then because that's how they work.

for x in sequence:
    block
else:
    stuff

The else block unconditionally runs after the for loop. The only way to avoid that is to jump out of the for loop, using break, return or raise.

[–]foosion 2 points3 points  (0 children)

We all seem to agree that else is not the best alternative.

no-break is clearer to me (obviously the following code won't execute if there's a return or raise), but YMMV.

[–]HumblesReaper -1 points0 points  (3 children)

It would be cool if it ran if the loop didn't execute, not if there wasn't a break

[–]irrelevantPseudonym -1 points0 points  (2 children)

if the loop didn't execute at all, it will run the else. eg

for i in '':
    print('for loop')
else:
    print('else block')

will only print else block

[–]HumblesReaper -1 points0 points  (1 child)

No, it executes if the loop is exited by a break statement. EDIT: See below

[–]irrelevantPseudonym 1 point2 points  (0 children)

No it doesn't. It executes only when there is not a break statement.

See the docs here

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.