Well, it depends on how you see it. You can look at elses like this (sorry to shout, its the only way to emphasize the code):
if condition: do_something() IF THE PREVIOUS CONDITION WAS FALSE: do_something_else()
Now there is an obvious similarity between if / else and try / except / else if you see the else statement as else for the except statement. Like this.
try: do_something() IF THERE WAS AN EXCEPTION: pass: IF THE PREVIOUS CONDITION WAS FALSE: do_something_else() finally: cleanup()
The same applies to else / for:
IF some_iterator IS NOT EMPTY: i = next(some_iterator) print(i) IF THE PREVIOUS CONDITION WAS FALSE: print("Iterator is empty!")
So, here we see that the other fundamentally works the same in all three cases.
But you can also see something else:
try: do_something() except someException: pass: IF NO EXCEPTION: do_something_else() finally: cleanup()
And then this is not the same, but different, because it is a kind of "if nothing else." You can see for / else in the same way:
for i in some_iterator: print(i) IF NO MORE ITERATING: print("Iterator is empty!")
But then again, given elif, then this way of seeing that it works for if / else:
if condition: do_something() elif otherconditaion: do_anotherthing() IF NO CONDITION WAS TRUE: do_something_else()
How you want to look at the other is up to you, but in both ways of viewing they still have similarities in all three cases.
Lennart Regebro
source share