Without the else clause you would need to set a flag and then check that later to see if any of the values met the condition.
If you make the search code a function, there’s no need for this kind of construct. Which is exactly why I’ve never used it. And as stated by @apy, even when I have thought about it (very rarely), I can’t remember the semantics and have to look it up. It’s forgotten for a reason: it’s unnecessary.
In a book I read recently (Barr’s “Find the Bug”) there was a section with a bunch of Python programs. The programs used for: ... else: ... liberally. It was awful code to read because it’s so un-idiomatic. I worked with Python for nearly 5 years and I’ve never seen it used in any library or example code. It’s like the author went out of his way to write crappy Python.
The else clause is nice with exceptions because it allows you to move all of the post-exception vulnerable code outside of the try block. Since it’s hard to tell what causes an exception, it makes it a bit easier to tell what might cause problems when you are scanning a block of code. E.g.,
try:
result = some_op()
some_other_op(result)
except:
print('You done a goof!')
vs
try:
result = some_op()
except:
print('You done a goof!')
else:
some_other_op(result)
Else clause is nice, but what a non-intuitive use of that keyword! They could easily have named it default or normal or any other word. Instead, they used else which is completely opposite to what else means in the context of if.
I never use it because I can literally never remember what it means I always have to look it up, which signals to me it’s not worth it.
If you make the search code a function, there’s no need for this kind of construct. Which is exactly why I’ve never used it. And as stated by @apy, even when I have thought about it (very rarely), I can’t remember the semantics and have to look it up. It’s forgotten for a reason: it’s unnecessary.
In a book I read recently (Barr’s “Find the Bug”) there was a section with a bunch of Python programs. The programs used
for: ... else: ...liberally. It was awful code to read because it’s so un-idiomatic. I worked with Python for nearly 5 years and I’ve never seen it used in any library or example code. It’s like the author went out of his way to write crappy Python.The else clause is nice with exceptions because it allows you to move all of the post-exception vulnerable code outside of the try block. Since it’s hard to tell what causes an exception, it makes it a bit easier to tell what might cause problems when you are scanning a block of code. E.g.,
vs
The forgotten “loop” feature in programming languages.
Else clause is nice, but what a non-intuitive use of that keyword! They could easily have named it default or normal or any other word. Instead, they used else which is completely opposite to what else means in the context of if.