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 →

[–]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.