Others have already explained the mechanics of while/for...else
, and the Python 3 language reference has the authoritative definition (see while and for), but here is my personal mnemonic, FWIW. I guess the key for me has been to break this down into two parts: one for understanding the meaning of the else
in relation to the loop conditional, and one for understanding loop control.
I find it's easiest to start by understanding while...else
:
while
you have more items, do stuff, else
if you run out, do this
The for...else
mnemonic is basically the same:
for
every item, do stuff, but else
if you run out, do this
In both cases, the else
part is only reached once there are no more items to process, and the last item has been processed in a regular manner (i.e. no break
or return
). A continue
just goes back and sees if there are any more items. My mnemonic for these rules applies to both while
and for
:
when break
ing or return
ing, there's nothing else
to do,
and when I say continue
, that's "loop back to start" for you
– with "loop back to start" meaning, obviously, the start of the loop where we check whether there are any more items in the iterable, so as far as the else
is concerned, continue
really plays no role at all.