The main secret of the else block in python loops

This is a short article for beginners. Surely you know that in Python for loops forand the whileunit 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 elseis at the same level with the block forand it seems that this is some kind of condition related to the list itself; for example, when I fordid not find any records. But it is enough to know the main secret of the block elsefor loops in order to never waste time on it again:



The block elseafter the loops does not belong to the loop itself, but to the operator break!



Indeed, the block elsewill be executed in any case, unless the execution of the loop was interrupted by the operator break, returnor 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.




All Articles