Many Python programmers are probably unaware that the syntax of while
loops and for
loops includes an optional else:
clause:
for val in iterable:
do_something(val)
else:
clean_up()
The body of the else
clause is a good place for certain kinds of clean-up actions, and is executed on normal termination of the loop: I.e., exiting the loop with return
or break
skips the else
clause; exiting after a continue
executes it. I know this only because I just looked it up (yet again), because I can never remember when the else
clause is executed.
Always? On “failure” of the loop, as the name suggests? On regular termination? Even if the loop is exited with return
? I can never be entirely sure without looking it up.
I blame my persisting uncertainty on the choice of keyword: I find else
incredibly unmnemonic for this semantics. My question is not “why is this keyword used for this purpose” (which I would probably vote to close, though only after reading the answers and comments), but how can I think about the else
keyword so that its semantics make sense, and I can therefore remember it?
I’m sure there was a fair amount of discussion about this, and I can imagine that the choice was made for consistency with the try
statement’s else:
clause (which I also have to look up), and with the goal of not adding to the list of Python’s reserved words. Perhaps the reasons for choosing else
will clarify its function and make it more memorable, but I’m after connecting name to function, not after historical explanation per se.
The answers to this question, which my question was briefly closed as a duplicate of, contain a lot of interesting back story. My question has a different focus (how to connect the specific semantics of else
with the keyword choice), but I feel there should be a link to this question somewhere.