Yes. All looping constructs in Python have an optional else clause that is executed when the loop condition becomes false (i.e., after the loop execution has been completed).
But.. That'd just be the same as putting code after the loop to begin with. Or will it, like, run even if you return from within the loop, or something like that?
The main use is that it doesn't run when you break out of the loop, which makes it useful for writing e.g. searches, where you want to do something when you didn't find the result.
No, it's almost the same as putting code after the loop. The difference is that you can access loop variables, so it's useful for when you want to do something using them but don't want to change their scope.
View all comments
Show parent comment
1
u/wiseIdiot Jan 03 '19
Yes. All looping constructs in Python have an optional
elseclause that is executed when the loop condition becomes false (i.e., after the loop execution has been completed).