This is a short article for beginners. Surely you know that in Python for loops for
and the while
unit is provided else
. And there is a lot of confusion with this block, because its action is at first glance unintuitive. You have to spend a little time or look into the documentation every time it comes across:
for f in files:
if f.uuid == match_uuid:
break
else:
raise FileNotFound()
When will there be an exception: when the file is not found? When was it found? When is the list empty? This question is difficult to answer, because the block else
is at the same level with the block for
and it seems that this is some kind of condition related to the list itself; for example, when I for
did not find any records. But it is enough to know the main secret of the block else
for loops in order to never waste time on it again:
The block else
after the loops does not belong to the loop itself, but to the operator break
!
Indeed, the block else
will be executed in any case, unless the execution of the loop was interrupted by the operator break
, return
or raise
.
If you read the example above like this: "if the file has the uuid we need, then end the loop, otherwise throw an exception", then everything falls into place.