I understand how this construct works:
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
But I don't understand why else
is used as the keyword here, since it suggests the code in question only runs if the for
block does not complete, which is the opposite of what it does! No matter how I think about it, my brain can't progress seamlessly from the for
statement to the else
block. To me, continue
or continuewith
would make more sense (and I'm trying to train myself to read it as such).
I'm wondering how Python coders read this construct in their head (or aloud, if you like). Perhaps I'm missing something that would make such code blocks more easily decipherable?
I agree, it's more like an 'elif not [condition(s) raising break]'.
I know this is an old thread, but I am looking into the same question right now, and I'm not sure anyone has captured the answer to this question in the way I understand it.
For me, there are three ways of "reading" the
else
inFor... else
orWhile... else
statements, all of which are equivalent, are:else
==
if the loop completes normally (without a break or error)
else
==
if the loop does not encounter a break
else
==
else not (condition raising break)
(presumably there is such a condition, or you wouldn't have a loop)So, essentially, the "else" in a loop is really an "elif ..." where '...' is (1) no break, which is equivalent to (2) NOT [condition(s) raising break].
I think the key is that the
else
is pointless without the 'break', so afor...else
includes:So, essential elements of a
for...else
loop are as follows, and you would read them in plainer English as:As the other posters have said, a break is generally raised when you are able to locate what your loop is looking for, so the
else:
becomes "what to do if target item not located".Example
You can also use exception handling, breaks, and for loops all together.
Result
Example
Simple example with a break being hit.
Result
Example
Simple example where there no break, no condition raising a break, and no error are encountered.
Result
A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.
For example assume that I need to search through a list and process each item until a flag item is found and then stop processing. If the flag item is missing then an exception needs to be raised.
Using the Python
for
...else
construct you haveCompare this to a method that does not use this syntactic sugar:
In the first case the
raise
is bound tightly to the for loop it works with. In the second the binding is not as strong and errors may be introduced during maintenance.I was just trying to make sense of it again myself. I found that the following helps!
• Think of the
else
as being paired with theif
inside the loop (instead of with thefor
) - if condition is met then break the loop, else do this - except it's oneelse
paired with multipleif
s!• If no
if
s were satisfied at all, then do theelse
.• The multiple
if
s can also actually be thought of asif
-elif
s!I read it something like:
If still on the conditions to run the loop, do stuff, else do something else.
I read it like "When the
iterable
is exhausted completely, and the execution is about to proceed to the next statement after finishing thefor
, the else clause will be executed." Thus, when the iteration is broken bybreak
, this will not be executed.Since the technical part has been pretty much answered, my comment is just in relation with the confusion that produce this recycled keyword.
Being Python a very eloquent programming language, the misuse of a keyword is more notorious. The
else
keyword perfectly describes part of the flow of a decision tree, "if you can't do this, (else) do that". It's implied in our own language.Instead, using this keyword with
while
andfor
statements creates confusion. The reason, our career as programmers has taught us that theelse
statement resides within a decision tree; its logical scope, a wrapper that conditionally return a path to follow. Meanwhile, loop statements have a figurative explicit goal to reach something. The goal is met after continuous iterations of a process.if / else
indicate a path to follow. Loops follow a path until the "goal" is completed.The issue is that
else
is a word that clearly define the last option in a condition. The semantics of the word are both shared by Python and Human Language. But the else word in Human Language is never used to indicate the actions someone or something will take after something is completed. It will be used if, in the process of completing it, an issue rises (more like a break statement).At the end, the keyword will remain in Python. It's clear it was mistake, clearer when every programmer tries to come up with a story to understand its usage like some mnemonic device. I'd have loved if they have chosen instead the keyword
then
. I believe that this keyword fits perfectly in that iterative flow, the payoff after the loop.It resembles that situation that some child has after following every step in assembling a toy: And THEN what Dad?